我正在嘗試從本地存盤(React Native Async Storage)獲取我的資料,然后將此資料推送到用于平面串列資料的陣列(arrayItems)中。我的問題是我的資料不會加載到平面串列中,我不知道該怎么做。我相信問題是因為我在呈現平面串列后首先從本地存盤中獲取資料。我曾嘗試在渲染平面串列之前使用 useEffect 獲取資料,但這似乎并不能解決問題。
我的代碼:
const [allKeys, setGetLocalStorageKeys] = useState([]);
let arrayItems= [];
const getLocalStorageKeys = async () => {
try {
setGetLocalStorageKeys(await AsyncStorage.getAllKeys());
} catch (e) {}
};
const getItem = async (prop) => {
try {
const item= await AsyncStorage.getItem(prop);
return item != null ? JSON.parse(item) : null;
} catch (e) {}
};
useEffect(() => {
try {
getLocalStorageKeys();
for (let i = 0; i < allKeys.length; i ) {
arrayItems.push(getItem(allKeys[i]));
}
} catch (e) {}
}, []);
return (
<View>
<FlatList
data={arrayItems}
renderItem={({ item }) => <Text>{item}</Text>}
keyExtractor={(item) => item}
/>
</View>
);
本地存盤https://github.com/react-native-async-storage/async-storage
uj5u.com熱心網友回復:
你可以添加另一個 useEffect 當你得到allKeys它會呼叫。
喜歡
useEffect(() => {
getLocalStorageKeys();
}, []);
useEffect(() => {
const tempArr = [];
if(allKeys.length > 0){
for (let i = 0; i < allKeys.length; i ) {
tempArr.push(getItem(allKeys[i]));
}
}
setArrayItems(tempArr);
}, [allKeys]);
uj5u.com熱心網友回復:
當您使用在 react-native 中發生變化的狀態時,請確保使用 useState 掛鉤。因為螢屏永遠不會重新渲染并顯示新資料。這是因為UseState 會導致您的組件在每次呼叫更新函式時重新渲染。
在下面做這樣的事情
const [allKeys, setGetLocalStorageKeys] = useState([]);
// Make sure to use useState for changing state in react
const [arrayItems,setArrayItems] = useState([]);
const getLocalStorageKeys = async () => {
try {
setGetLocalStorageKeys(await AsyncStorage.getAllKeys());
} catch (e) {}
};
const getItem = async (prop) => {
try {
const item= await AsyncStorage.getItem(prop);
return item != null ? JSON.parse(item) : null;
} catch (e) {}
};
useEffect(() => {
const fetch = async = ()=>{
try {
getLocalStorageKeys();
// Use a temp arr
const tempArr = [];
for (let i = 0; i < allKeys.length; i ) {
const value = await getItem(allKeys[i]);
tempArr.push(value);
}
// Set the state
setArrayItems(tempArr);
} catch (e) {
console.log(e);
}
}
// Call function
fetch();
}, [allKeys]);
return (
<View>
<FlatList
data={arrayItems}
renderItem={({ item }) => <Text>{item}</Text>}
keyExtractor={(item) => item}
/>
</View>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/420551.html
標籤:
上一篇:react-native-video5.2.0Android構建錯誤RNC0.66.3
下一篇:顫振和飛鏢中的空安全
