假设你有一个这样的组件:
function MyComponent({ index }) {
const [data, setData] = useState('');
useEffect(() => {
(async function() {
const result = await fetchData(index);
setData(result);
})();
}, [index]);
return <h1>{data}</h1>;
}每当索引发生变化时,我们都会重新获取数据并呈现它。我如何缓存它,这样我们就不需要从之前重新获取相同的索引了?
发布于 2021-09-19 20:52:38
您想要您的结果,如下所示:
const cache = {};
async function memoFetch(index) {
if (cache[index]) {
return cache[index];
}
const data = fetchData(index);
cache[index] = data;
return data;
}
function MyComponent({ index }) {
const [data, setData] = useState('');
useEffect(() => {
(async function() {
const result = await memoFetch(index);
setData(result);
})();
}, [index]);
return <h1>{data}</h1>;
}发布于 2021-09-23 21:24:07
const MyComponentCacheContext = React.createContext() ;
2.创建组件缓存提供程序,并为缓存提供初始值{}(空对象):
function MyComponentCacheProvider (props){
//we create this in step 3
const [cache,dispatch]= React.useReducer(MyComponentCacheReducer,{})
const value =[cache,dispatch]
return <MyComponentCacheContext value={value} {...props}/>
}3.我们将使缓存看起来像这个=> {{index:data},{index:data},...},因此创建一个返回所需形状的组件缓存Reducer:
function MyComponentCacheReducer (state,action) {
switch(action.type){
case 'ADD-TO-CACHE':
return {...state,[action.index]:action.data}
default :{
throw new Error (`unhandled action type ${action.type}`)
}
}
}4.让我们将上面的所有代码放在一个客户钩子中,这样我们就可以使其可重用:
function useMyComponentCache(){
const MyContext = React.useContext(MyComponentCacheContext)
if(!MyContext){
throw new Error (`useMyComponentCache must be within a MyComponentCacheProvider`)
}
return MyContext
}5.让我们定制组件函数,这样我们就可以使用上面的代码:
function MyComponent({ index }) {
const [data, setData] = useState('');
const [cache ,dispatch]= useMyComponentCache()
useEffect(() => {
if(cache[index]){
return setData(cache[index])
}else{
//here we fetch data --then--> we store it into the cache immedialty
const dataFetcher=fetchData(index).then(
data =>{
dispatch({type:'ADD-TO-CACHE',index,data})
return data
}
)
// updating state
const PromiseHandler =React.useCallback(
promise=>{
promise.then(
data => {
setData(data)
},
)
}
,[setData])
// Execution-Time
PromiseHandler(dataFetcher)
}
}, [cache,dispatch,index,PromiseHandler,setData]); // i assume that fetchData is
//a stable internal module so i didn t put it to the dependecies list
return <h1>{data}</h1>;
}6.呈现步骤:将组件放入CacheProvider!
function App(){
return ( <MyComponentCacheProvider>
<MyComponent index={0} />
</MyComponentCacheProvider>
)
}https://stackoverflow.com/questions/69246976
复制相似问题