我正在使用 APISAUCE 從節點服務器獲取回應,然后在 FlatList 中顯示資料。我實際上想要做的是將此回應存盤在 AsyncStorage 中作為快取,因此當應用程式處于離線狀態時,要在 FlatList 中顯示的資料必須從 AsyncStorage 中檢索,而不是從服務器中獲取。
這是我的代碼實作:
import { create } from "apisauce";
const apiClient = create({
baseURL : "http://192.168.10.9:9000/api"
});
export default apiClient;
import apiClient from "./client";
const endpoint = "/listings";
const getListings =() =>{
return apiClient.get(endpoint);
}
export default {getListings};
import React , { useState } from "react";
export default useAPI=(API)=>
{
const[data,setData]=useState([]);
const [error , setError]=useState(false);
const [isLoading ,setLoading]=useState();
const request = async()=> {
setLoading(true);
const response = await API();
setLoading(false);
if(!response.ok) return setError(true);
setError(false);
setData(response.data);
}
return {error , data ,isLoading ,request }
}
function ListingScreen({navigation}) {
const loadListing= useAPI(getListings.getListings);
useEffect(()=>{
loadListing.request();
}, []);
return (
<View style={styles.container} >
{loadListing.error && (
<View style={{marginTop:60}}>
<Text style={{textAlign:"center"}}>
Cannot Retrieve Data From Server
</Text>
<AppButton title="retry" onPress={loadListing.request} />
</View>
)}
{loadListing.isLoading ? <View>
<ActivityIndicator animating={true} size={80} color="grey" />
</View> :
<FlatList data={loadListing.data} keyExtractor={list=>list.id.toString()}
renderItem ={({item}) => <Card title={item.title} subtitle={"$" item.price}
image={item.images[0].url} onPress={()=>navigation.navigate("ListingDetails" ,item )} />
} />
}
</View>
);
}
uj5u.com熱心網友回復:
當用戶打開應用程式時:
- 首先檢查本地存盤
- 如果那里存在資料,則決議資料,然后將資料呈現到您的平面串列。
- 如果未找到,則請求您的 url,然后將資料轉換為字串并存盤在存盤中。最后更新您的資料。
import React , { useState } from "react";
export default useAPI=(URL)=>
{
const[data,setData]=useState([]);
const [error , setError]=useState(false);
const [isLoading ,setLoading]=useState();
const _getDataFromStorage = async () => {
/*
- Getting data from async storage
- If data wasn't null, Parse data for covering string to object
and update your states and return true
- If data was null return false*/
}
const request = async ()=> {
try {
if (await _getDataFromStorage()) {
return;
}
setLoading(true);
const response = await fetch(
URL,
//your request options
);
setLoading(false);
if(!response.ok)
return setError(true);
const responseJson = await response.json();
setError(false);
setData(responseJson.data);
} catch (error) {
console.error(error);
setError(true);
}
}
return {error , data ,isLoading}
}
并執行您的其他實作。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/351493.html
標籤:反应原生 反应钩子 react-native-flatlist 异步存储
