React Native如何向AsyncStorage存储的已有数组追加新元素?
问题解决实现方案
错误点说明
AsyncStorage.getItem为异步方法,未加await时获取的是Promise对象而非实际存储的内容- AsyncStorage仅支持存储字符串类型数据,直接拼接字符串未做JSON序列化、反序列化处理,会导致存储内容失去数组结构
正确实现代码
saveData = async () => { try { // 取出存储内容,转成数组,无历史存储时默认空数组 const storedCountries = await AsyncStorage.getItem('countries'); const countries = storedCountries ? JSON.parse(storedCountries) : []; // 追加新的country项 countries.push(this.state.country); // 数组转JSON字符串后存入AsyncStorage await AsyncStorage.setItem('countries', JSON.stringify(countries)); alert('Data successfully saved'); console.log('countries', countries); } catch (e) { alert(e); } }
配套取值写法
后续需要读取countries数组使用时,对应写法如下:
const getSavedCountries = async () => { try { const storedCountries = await AsyncStorage.getItem('countries'); return storedCountries ? JSON.parse(storedCountries) : []; } catch (e) { alert(e); return []; } }
内容的提问来源于stack exchange,提问作者noman akram
相关产品推荐
相关产品推荐

