TypeError: Cannot create property '1' on string ''
来源:8-12 同步文章缓存状态

atmonsters
2020-09-27
代码是跟着老师敲的,大概知道错误在postsCollected上,但想不通怎么改,老版也有类似提问,但新版的代码有些不同,本人菜鸟,麻烦大佬指点下
// pages/post-detail/post-detail.js
import {postList} from '../../data/data.js'
Page({
/**
* 页面的初始数据
*/
data: {
postData:{},
collected:false,
_pid:null,
_postsCollected:{}
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
const postData = postList[options.pid]
this.data._pid = options.pid
const postsCollected = wx.getStorageSync('posts_collected') //个人感觉错误在本行
this.data._postsCollected = postsCollected
let collected = postsCollected[this.data._pid]
if(collected === undefined){
collected = false
}
this.setData({
postData,
collected
})
},
onCollect(event){
const postsCollected = this.data._postsCollected
postsCollected[this.data._pid] = !this.data.collected
this.setData({
collected:!this.data.collected
})
wx.setStorageSync('posts_collected', postsCollected)
},
5回答
-
首先找到这个错误发生的代码行数
在这个代码行数之前的每一步console.log打印变量 逐步分析,就能找到哪里写错了
032020-10-12 -
慕莱坞1351805
2020-10-28
删除缓存数据后会报这个错误,原因:
1,const postsCollected = wx.getStorageSync('posts_collected') 这行代码查询缓存数据结果为空字符串
2,this.data._postsCollected = postsCollected 这行代码会把 this.data._postsCollected 赋值为空字符串
3,所以在onCollect函数中我们获取的_postsCollected变量是空字符串: Cannot create property '1' on string ''
const postsCollected = this.data._postsCollected
postsCollected[this.data._pid] = !this.data.collected解决方法:
修改 const postsCollected = this.data._postsCollected 为 const postsCollected = this.data._postsCollected || {}
612021-03-01 -
_简简丶单单_蓝颜
2020-10-13
要转换类型
10 -
3301942
2020-10-12
加了一个判断
onCollect: function(event) {
if (this.data._articleCollected){
var articleCollected = this.data._articleCollected
}else{
var articleCollected = {}
}
}
10 -
慕田峪8097929
2020-09-29
没有缓存的时候获取到的是空字符串不是undefined
112020-09-29