React Native中MMKV读取数据报错:Cannot read property 'name' of undefined
问题:读取JSON的
goal.name时报错TypeError: Cannot read property 'name' of undefined 场景说明
我有如下格式的JSON数据:
{ "id": 18, "goal": { "name": "Test" } }
使用MMKV将该JSON数据存储到本地。从Page1将ID(此例中为18)传递到Page2,在Page2中读取该JSON并尝试显示其中的name字段。
出现的错误
TypeError: Cannot read property 'name' of undefined
明明该属性存在,我完全搞不懂为什么会报错!
报错的Page2代码
export default function Page2() { const [json, setJson] = useState({} as any); const { id } = useLocalSearchParams(); useEffect(() => { if (id) { const jsonRecords = storage.getString('records') const records = JSON.parse(jsonRecords || '{}'); const record = records.find((record: any) => record.id == id); console.log(record); // 这里能正常打印出上述格式的JSON setJson(record); } }, [id]); return ( <SafeAreaView> <Text>{json.goal.name}</Text> {/* 此行报错 */} </SafeAreaView> ); }
可正常运行的写法
奇怪的是,改成下面的写法就可以正常运行,但我不明白原因:
export default function Page2() { const [json, setJson] = useState({} as any); const [name, setName] = useState(null); const { id } = useLocalSearchParams(); useEffect(() => { if (id) { const jsonRecords = storage.getString('records') const records = JSON.parse(jsonRecords || '{}'); const record = records.find((record: any) => record.id == id); console.log(record); // 这里能正常打印出上述格式的JSON setJson(record); setName(record.goal.name); // 在此处设置name } }, []); return ( <SafeAreaView> <Text>{name}</Text> {/* 此行正常运行 */} </SafeAreaView> ); }
疑问
我到底哪里出错了?
内容的提问来源于stack exchange,提问作者user023425
相关产品推荐
相关产品推荐

