irychen / keepalive-for-react

React KeepAlive is a component that can cache the state of the component and reuse it when needed.
MIT License
162 stars 32 forks source link

大哥,能不能手把手教学一下,不太会用 #6

Closed nieyunliang closed 4 months ago

nieyunliang commented 4 months ago
image image

跟着教程走了,但是页面反而不渲染了

irychen commented 4 months ago

使用 useOutlet 这个hook


import {useLocation, useOutlet} from 'react-router-dom';

function BasicLayoutWithCache() {

  const outlet = useOutlet();
  const location = useLocation();

  /**
   * to distinguish different pages to cache
   */
  const cacheKey = useMemo(() => {
    return location.pathname + location.search;
  }, [location]);

  return <div>
    <KeepAlive activeName={cacheKey} max={10} strategy={'LRU'}>
      {outlet}
    </KeepAlive>
  </div>
}
nieyunliang commented 4 months ago

数据出来了,但是现在出现另外一个问题,我多个路由使用同一个组件的时候,数据没有更新,他们用了同一份数据,这种情况要如何处理呢

irychen commented 4 months ago

你需要给出具体代码,最好是Codesandbox之类的在线预览的 https://codesandbox.io/

nieyunliang commented 4 months ago

https://codesandbox.io/p/sandbox/bitter-leaf-ttmq2f?file=%2Fsrc%2FListTemp.js%3A1%2C4-1%2C48

代码放上去了,不过因为是部分组件代码,所以没法运行。 里面的ListTemp组件就是共用的列表组件,目前只是这个组件有问题,在缓存的路由之间互相切换不会更新数据,除非是打开新的路由,否则就只会用到最新路由的数据

irychen commented 4 months ago

你需要监听页面是否被激活打开,然后重新获取数据

import { useKeepAliveContext } from 'keepalive-for-react';

function CachedComponent() {
  const { active } = useKeepAliveContext();

  useEffect(() => {
    if (active) {
      // send request to fetch data
    }
  }, [active]);

  return <div>{/* ... */}</div>;
}

或者

import { useEffectOnActive } from 'keepalive-for-react';

function CachedComponent() {

  useEffectOnActive((active) => {
    if (active) {
       // send request to fetch data
    }
  }, false, []);

  return <div>{/* ... */}</div>;
}

实现细节 https://github.com/irychen/keepalive-for-react/blob/main/src/components/KeepAliveProvider/index.tsx