在移动端中,用户访问了一个列表页,上拉浏览列表页的过程中,随着滚动高度逐渐增加,数据也将采用触底分页加载的形式逐步增加,列表页浏览到某个位置,用户看到了感兴趣的项目,点击查看其详情,进入详情页,从详情页退回列表页时,需要停留在离开列表页时的浏览位置上,react中没有现成得保留组件状态得方法。
但是有第三方库 react-activation 个人感觉这个好用!
提示:以下是本篇文章正文内容,下面案例可供参考
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
到此这篇关于react实现组件状态缓存的示例代码的文章就介绍到这了,更多相关react 组件状态缓存内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!