【问题标题】:Convert String returned by Promise to Array将 Promise 返回的字符串转换为数组
【发布时间】:2019-04-24 11:51:33
【问题描述】:

我在将 promise 返回的字符串转换为数组时遇到问题。 Promise 由 React Native 中的 AsyncStorage 返回。我已经尝试过 JSON.parse 和 .split() 但我认为我没有正确使用它们。之后我需要能够从数组中调用特定的键值对。如果您有任何建议,请告诉我。我在控制台日志中包含了我的代码、错误截图和返回值

onLocationsSelectionChange = (locationsSelected) => {
console.log("does this work", locationsSelected, this.state.locationsSelected.length)
AsyncStorage.setItem('@MySuperStore:locationsSelected', JSON.stringify(this.state.locationsSelected));

const myArray = AsyncStorage.getItem('@MySuperStore:locationsSelected')
console.log('test Array', (myArray));
console.log('myArray', JSON.parse(myArray))
this.setState({locationsSelected});

};

图片:

【问题讨论】:

  • myArray 不是数组,而是Promise
  • 谢谢@PatrickRoberts!我知道它是由 AsyncStorage 返回的 Promise。它在我的代码中以数组开始,然后在第 3 行转换为字符串以保存到 AsyncStorage。当我使用 AsyncStorage.getItem 检索数据时,它以字符串形式返回,因为这就是我所知道的 AsyncStorage保存其数据。我的问题是将数据从承诺转换回数组

标签: arrays json react-native promise


【解决方案1】:

AsyncStorage 文档中,您应该得到这样的项目:

_retrieveData = async () => {
  try {
    const value = await AsyncStorage.getItem('TASKS');
    if (value !== null) {
      // Here use JSON.parse(value)
    }
   } catch (error) {
     // Error retrieving data
   }
}

【讨论】:

  • 谢谢,这很有道理 Oma!
猜你喜欢
  • 1970-01-01
  • 2022-10-17
  • 1970-01-01
  • 2012-10-27
  • 1970-01-01
  • 2016-04-11
  • 2013-05-12
  • 2013-05-05
  • 2014-02-21
相关资源
最近更新 更多