从AsyncStorage取数据到FlatList时字段读取失败问题
React Native: AsyncStorage读取的数据无法在FlatList中渲染字段
使用硬编码的DATA数组时,FlatList可以正常渲染列表项;但从AsyncStorage读取数据后,虽然控制台能输出4个对象的字符串,且应用能识别到数组长度为4,但每个对象的字段(如setup、punchline)均为undefined,无法正常渲染。
控制台日志输出:
LOG all bits: {"setup":"Setup 1","punchline":"Punchline 1","id":0},{"setup":"Setup 2","punchline":"Punchline 2","id":1},{"setup":"Setup 3","punchline":"Punchline 3","id":2},{"setup":"Setup4","punchline":"Punchline4","id":3}
相关代码:
import React, { useState, useEffect } from "react"; import AsyncStorage from "@react-native-async-storage/async-storage"; import { StyleSheet, View, FlatList, Button} from "react-native"; import Item from '../Components/item'; // const DATA = [ // { // "id": 0, // "punchline": "To get to the other side", // "setup": "Why I the chicken cross the road", // "title": "Chicken Butt", // "status": "draft", // }, // { // "id": 1, // "punchline": "2To get to the other side", // "setup": "2Why I the chicken cross the road jdkjkjsjkjjkdsl", // "title": "Chicken Butt Part Duex", // "status": "Active", // }, // { // "id": 2, // "punchline": "3To get to the other side", // "setup": "3Why I the chicken cross the road", // "title": "Bit Title", // "status": "test", // }, // ]; export default function BitList({navigation}) { const [bitList, setBitList] = useState(null); const getIds = async () => { try { let storedIds = JSON.parse(await AsyncStorage.getItem("@bit-ids")); if (!storedIds) { return (storedIds = []); } else { return storedIds; } } catch (e) { console.error("Something happened while getting ids: " + e); } }; const getAllBits = async () => { const ids = await getIds(); const bitIds = []; if (ids) { ids.forEach((id) => { bitIds.push("@bit-" + id); }); try { const allBits = await getMultipleBits(bitIds); console.log("all bits: " + allBits) setBitList(allBits); } catch (e) { console.error(e); } } }; const getMultipleBits = async (bitIds) => { const allBits = []; try { const savedData = await AsyncStorage.multiGet(bitIds); savedData.forEach((bit) => { allBits.push(bit[1]); }); return allBits; } catch (e) { console.error(e); } }; useEffect(() => { getAllBits(); // (async () => { // const awaitedVal = await getAllBits(); // console.log("lg :" +awaitedVal) // setBitList(awaitedVal); // })(); // setBitList(DATA) // console.log(DATA); }, []); return ( <View style={styles.container}> {bitList && ( <FlatList data={bitList} renderItem={({ item }) => ( <Item setup={item.setup} punchline={item.punchline} status={item.status ? item.status : "none"} bitId={item.id} navigation={navigation} /> )} keyExtractor={(item) => item.id} /> )} {/* <Button title="refresh" onPress={() => []} /> */} </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, }, });
已尝试的解决方法:
- 使用
JSON.parse和JSON.stringify处理读取到的数据 - 将异步读取代码从全局文件移到组件内部
以上操作均未解决问题。
内容的提问来源于stack exchange,提问作者Evan G
相关产品推荐
相关产品推荐

