尝试从
AsyncStorage
检索数据以放入 FlatList
。使用硬编码数据对象 DATA
效果很好。它正在读取 AsyncStorage
中的数据集,这似乎是一个问题。我可以在控制台日志中看到数据,它看起来是正确的:
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}
它只是不读取里面的各个按键。他们都是
undefined
。
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,
},
});
我尝试过解析、字符串化。我最初将所有异步调用都放在自己的文件中,并将它们导出以在整个应用程序中使用。将这些特定调用移至实际组件中,但仍然是同样的问题。
如果您在从 AsyncStorage 检索数据并将其显示在 FlatList 中时遇到问题,尽管数据已正确记录,但数据转换或将数据设置到 FlatList 的方式可能存在问题。
以下是如何从 AsyncStorage 检索数据并将其显示在 FlatList 中的示例:
import React, { useEffect, useState } from 'react';
import { View, FlatList, Text } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
const YourComponent = () => {
const [data, setData] = useState([]);
useEffect(() => {
// Function to retrieve data from AsyncStorage
const retrieveData = async () => {
try {
// Retrieve data from AsyncStorage
const storedData = await AsyncStorage.getItem('your_key'); // Replace 'your_key' with your actual AsyncStorage key
if (storedData !== null) {
// Parse the retrieved data (assuming it's stored as a string)
const parsedData = JSON.parse(storedData);
setData(parsedData); // Set the retrieved data to the state
}
} catch (error) {
console.log('Error retrieving data:', error);
}
};
retrieveData(); // Call the function to retrieve data when component mounts
}, []); // Empty dependency array ensures this effect runs only once
return (
<View>
<FlatList
data={data}
keyExtractor={(item, index) => index.toString()}
renderItem={({ item }) => (
<Text>{item.name}</Text> // Adjust this based on your data structure
)}
/>
</View>
);
};
export default YourComponent;
1 AsyncStorage Key: 将“your_key”替换为您用于在 AsyncStorage 中存储数据的实际密钥。
2 数据结构: 调整 FlatList 中的 renderItem 函数以匹配您的数据结构。在示例中,它假设数据数组中的每个项目都有一个 name 属性。
通过使用 setData(parsedData) 将检索到的数据设置为状态,它应该更新状态并触发重新渲染,在 FlatList 中显示数据。如果数据在控制台中正确显示,但在 FlatList 中未正确显示,请确保数据结构正确,并且 FlatList 正确接收和渲染数据。