编写收藏功能按钮时候,收藏后退出报错,求解答
发布于 7 年前 作者 kpeng 11321 次浏览 来自 问答

WAService.js:3 thirdScriptError
Cannot read property ‘0’ of undefined;at “pages/posts/post-detail/post-detail” page lifeCycleMethod onLoad function
TypeError: Cannot read property ‘0’ of undefined

代码:

//post_detail.js

var postsData = require("…/…/…/data/posts_data.js")

Page({
 
  onLoad:function(option){
    var postId=option.id;
    this.data.currentPostId = postId;
    var postData=postsData.postList[postId];
    this.setData({
      postData: postData
    })

    var postsCollected = wx.getStorageSync(‘posts_collected’);
    if (postsCollected) {
      var postCollected = postCollected[postId];
      this.setData({
        collected: postCollected
      })
    }
    else{
      var postsCollected = {};
      postsCollected[postId] = false;
      wx.setStorageSync(‘posts_collected’, postsCollected);
    }
  },
  onCollectionTap:function(event){
    var postsCollected = wx.getStorageSync(‘posts_collected’);
    var postCollected = postsCollected[this.data.currentPostId];
    postCollected = !postCollected;
    postsCollected[this.data.currentPostId] = postCollected;
    wx.setStorageSync(‘posts_collected’, postsCollected);
    this.setData({
      collected: postCollected
    }),

    wx.showToast({
        title:postCollected?“收藏成功”:“取消成功”
    })
  }

})

post_detail.wxml

<view class=“container”>
  <image class=“head-image” src="{{postData.headImgSrc}}"></image>
  <image class=“audio” src="/image/music/music-start.png"></image>
  <view class=“author-date”>
    <image class=“avatar” src="{{postData.avatar}}"></image>
    <text class=“author”>{{postData.author}}</text>
    <text class=“const-text”>发表于</text>
    <text class=“date”>{{postData.dateTime}}</text>
  </view>
  <text class=“title”>{{postData.title}}</text>
  <view class=“tool”>
    <view class=“circle-img”>
      <image wx:if="{{collected}}" catchtap=“onCollectionTap”  src="/image/icon/collection.png"></image>
      <image wx:else catchtap=“onCollectionTap” src="/image/icon/collection-anti.png"></image>
      <image class=“share-img” src="/image/icon/share.png"></image>
    </view>
    <view class=“horizon”></view>
  </view>
  <text class=“detail”>{{postData.detail}}</text>
</view>

回到顶部