irychen / keepalive-for-react

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

这种页面级别如何使用啊?试着用KeepAlive包起来会报错 #13

Closed Jordonwang closed 4 months ago

Jordonwang commented 4 months ago
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <React.StrictMode>
    <Provider store={store}>
      <RouterProvider router={router} />
    </Provider>
  </React.StrictMode >
)
irychen commented 4 months ago

路由中需要这样使用

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