【发布时间】:2017-03-08 13:31:18
【问题描述】:
您好,我在向 AsyncStorage 中的数组添加值时遇到问题。
AsyncStorage.getItem('savedIds', (err, result) => {
const id = '1';
if (result !== null) {
console.log('Data Found', result);
result = JSON.parse(result);
result.push(id);
AsyncStorage.setItem('savedIds', JSON.stringify(result));
} else {
console.log('Data Not Found');
AsyncStorage.setItem('savedIds', id);
}
});
AsyncStorage.getItem('savedIds', (err, result) => {
console.log(result);
});
设置初始 ID 后,我收到错误“result.push”不是函数。我需要改变什么来解决这个问题?还是有更优雅的解决方案?
【问题讨论】:
-
typeof 结果不是数组。所以它抛出错误“result.push”不是一个函数
-
控制台
typeof result -
未定义,如何将第一个 id 设置为数组的一部分,以便将数据推送到其中。
-
使用
result = JSON.parse(result) || [];