English 中文(简体)
如何应对部件堆积?
原标题:How to cache react component fetches?

让我说,你有这样一个组成部分:

function MyComponent({ index }) {
  const [data, setData] = useState(  );

  useEffect(() => {
    (async function() {
      const result = await fetchData(index);
      setData(result);
    })();
  }, [index]);

  return <h1>{data}</h1>;
}

每当指数变化时,我们将重新计算数据并公布数据。 我怎样才能这样做,以便我们不必从前重新计算同样的指数?

问题回答

页: 1 阁下的成果如下:

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>;
}

  1. create a component cache Context:

const MyComponentCacheContext = React.createContext() ;

2. 设定一个构成部分Cache Provider,并给切一个内值{}(危险目标):

 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.we will make the cache look like this => {{index:data},{index:data},...}so create a component cache Reducer that return the desired shape :

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.let s make all the code above within a custome hook so we can make it reusable:

function useMyComponentCache(){
const MyContext = React.useContext(MyComponentCacheContext)
if(!MyContext){
    throw new Error (`useMyComponentCache must be within a MyComponentCacheProvider`)
}
return MyContext
}

5.let s customize your Component function so we can use the code above :

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.rendering step :put your component within CacheProvider !!!

function App(){

return ( <MyComponentCacheProvider>
            <MyComponent index={0} /> 
         </MyComponentCacheProvider>
       )
}

I haven t seen better implementations than Tanstack s React Query. Here is an example, it combines memoization, loading indicators, stale times, cache times, and even local storage persistence. Here is a quick example:

  const { isLoading, isFetching, isIdle, error, data: postsData } = useQuery({
    queryKey: [ feed , { userId, profile }],
    queryFn: fetchInitialData,
    staleTime: 0,
    cacheTime: 1000 * 60 * 60 * 4,
    refetchInterval: 1000 * 10, // refetch every 5 seconds
    refetchIntervalInBackground: false,
    refetchOnMount: "always",
    refetchOnWindowFocus: "always",
    refetchOnReconnect: "always",
    suspense: false
  });

详情见https://tanstack.com/query/v4





相关问题
How to use one react app into another react app?

I have two react apps, parent app and child app. and child app have an hash router. I have build the child app using npm run build, It creates build folder. That build folder moved into inside the ...

how to get selected value in Ant Design

I want to print the selected value, and below is my option list: const vesselName = [ { value: 0 , label: ALBIDDA , }, { value: 1 , label: ALRUMEILA , }, { value: 2 ,...

How to add a <br> tag in reactjs between two strings?

I am using react. I want to add a line break <br> between strings No results and Please try another search term. . I have tried No results.<br>Please try another search term. but ...

热门标签