irychen / keepalive-for-react

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

How to exclude/include pages to cache in router keep alive #1

Closed existenceO closed 8 months ago

existenceO commented 8 months ago

你好! 想问一下,如果包裹的是router的useOutlet的话,可以怎么include/exclude page呢? 我下载的包版本是v2.0.0

router/index.js
  const router = createBrowserRouter([
    {
      path: '/',
      Component: Root,
      children: [
        {
          path: '/',
          element: <Home/>,
        },
        {
          path: 'product-detail/:id',
          element: <ProductDetail />
        }
      ]
    }
  ])

root.tsx
...
const outlet = useOutlet()
...
<KeepAlive aliveRef={keepAliveRef} max={5} activeName={cacheKey}>
        {outlet}
      </KeepAlive>
...
irychen commented 8 months ago

reference: https://github.com/irychen/keepalive-for-react/blob/main/src/components/KeepAlive/index.tsx

<KeepAlive activeName={cacheKey}
       exclude={[/\/exclude-counter/]}
       max={10} strategy={'LRU'}>
    {outlet}
</KeepAlive>
KeepAlive.props.include or KeepAlive.props.exclude Array<string | RegExp> | string | RegExp;
irychen commented 8 months ago

Accordingt to your code, you may need this.

 <KeepAlive activeName={cacheKey}
             exclude={[/^\/product-detail\//]}
             max={10} strategy={'LRU'}>
      {outlet}
  </KeepAlive>
existenceO commented 8 months ago

Thanks!