【发布时间】: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