react-native - 有什么方法可以将从 APISAUCE API 接收到的响应存储到异步存储中作为缓存并在 React Native 的平面列表中显示
问题描述
我正在使用 APISAUCE 从节点服务器获取响应,然后在 FlatList 中显示数据。我实际上想要做的是将此响应作为缓存存储在 AsyncStorage 中,因此当应用程序处于脱机状态时,必须从 AsyncStorage 中检索要在 FlatList 中显示的数据,而不是从服务器中获取它。
这是我的代码实现:
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>
);
}
解决方案
当用户打开应用程序时:
- 首先检查本地存储
- 如果那里存在数据,请解析数据,然后将数据呈现到您的平面列表中。
- 如果未找到,则向您的 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}
}
并做你的其他实现。
推荐阅读
- typescript - 如何在 TypeScript 中获取泛型的特定“实例”的“内部类型”
- laravel - 选择框时需要自定义验证规则
- ios - 服务器上的多个会话 - Alamofire
- jenkins - 在詹金斯管道中运行 npm install 的问题
- javascript - 像按钮的 onclick 函数这样的 DOM 元素是否需要显式发送事件作为参数?
- powershell - 从路径中删除最后一个扩展名
- swift - 注册和写入数据库后如何/何时删除 Firebase Auth 侦听器?
- ios - 如何在 UIStackView 中隐藏滚动条?
- azure - LUIS API - 检索所有端点话语及其分数
- oracle - 使用 Oracle 和 SUM 查询连接 2 个表?