我正在使用APISAUCE从Node获得响应,然后在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>
);
}发布于 2021-11-06 07:28:45
当用户打开应用程序时:
如果存在数据,
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://stackoverflow.com/questions/69861890
复制相似问题