AsyncStorage存储数组格式错误,新增日记条目时出现嵌套异常
问题修复方案
根因说明
你遇到的多层嵌套数组格式异常完全是代码中错误的逻辑导致的,具体问题如下:
- 已经对从AsyncStorage取出的字符串做了
JSON.parse得到alldays数组,后续又对已经是对象/数组类型的alldays再次执行JSON.parse,还把解析结果push到原alldays数组里,这是数组层层嵌套的直接原因 - 没有处理首次写入时存储为空的场景,此时
alldays为null,直接调用push会抛出异常 - 数组push是同步方法,不需要加
await,多余的异步操作没有意义
修复后代码
async function createDay(date: string, journal: string, name: string) { try { // 读取存储内容 const getalldays = await AsyncStorage.getItem('@journal') // 解析内容,为空则初始化空数组 const alldays = getalldays ? JSON.parse(getalldays) : [] // 新增条目 const newDay = { date: date, value: journal, name: name } alldays.push(newDay) // 回写存储 await AsyncStorage.setItem('@journal', JSON.stringify(alldays)) // 测试打印 const newall = await AsyncStorage.getItem('@journal') console.log(newall) } catch (error) { console.error(error) } }
修复后存储的格式会为标准的单层对象数组,符合预期:
[ {"date":"t","value":"t","name":"t"}, {"date":"p","value":"p","name":"p"}, {"date":"h","value":"h","name":"h"} ]
内容的提问来源于stack exchange,提问作者robinnlmn
相关产品推荐
相关产品推荐

