这篇文章主要介绍“react如何实现组件状态缓存”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“react如何实现组件状态缓存”文章能帮助大家解决问题。
一、安装第三方库
npm i react-activation
二、配置操作
1、在根目录引入 AliveScope
import {AliveScope} from 'react-activation'
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<Provider store={store}>
<AliveScope>
<App />
</AliveScope>
</Provider>
</BrowserRouter>
);
2、在需要保留状态得组件上使用 KeepAlive 包裹
我要保留cate组件得状态所以使用keepAlive包裹cate组件
import { Navigate } from 'react-router-dom'
import {KeepAlive} from 'react-activation'
// 懒加载路由需要放到普通路由最下面
import NotFound from '../pages/notFound'
import Layout from '../pages/Layout'
import Home from '../pages/Layout/Home'
import Cate from '../pages/Layout/Cate'
import CateItem from '../pages/Layout/CateItem'
import ShopCar from '../pages/Layout/ShopCar'
import Me from '../pages/Layout/Me'
import ItemAll from '../pages/ItemAll'
const routerList = [
{ path: '/', element: <Navigate to="/home" /> },
{
path: '/home', element:<Layout />,children:[
{index:true, element: <Navigate to="index" />},
{path:'index', element: <Home />},
{path:'cate', element: <KeepAlive><Cate /></KeepAlive>}, //这里需要包裹
{path:'cateItem', element: <CateItem />},
{path:'shopcar', element: <ShopCar />},
{path:'Me', element: <Me />},
]
},
{ path: '*', element: <NotFound /> }
]
export default routerList
版权声明:除特别声明外,本站所有文章皆是本站原创,转载请以超链接形式注明出处!