【问题标题】:React Native AsyncStorage: Push to an array with a keyReact Native AsyncStorage:使用键推送到数组
【发布时间】: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) || [];

标签: react-native asyncstorage


【解决方案1】:
AsyncStorage.getItem('savedIds', (err, result) => {
  const id = [1];
  if (result !== null) {
    console.log('Data Found', result);
    var newIds = JSON.parse(result).concat(id);
    AsyncStorage.setItem('savedIds', JSON.stringify(newIds));
  } else {
    console.log('Data Not Found');
    AsyncStorage.setItem('savedIds', JSON.stringify(id));
  }
});

【讨论】:

    猜你喜欢
    • 2020-05-12
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 2019-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多