文章詳情頁
react實(shí)現(xiàn)組件狀態(tài)緩存的示例代碼
瀏覽:113日期:2022-06-01 17:55:59
目錄
- 前言
- 一、安裝第三方庫
- 二、配置操作
- 總結(jié)
前言
在移動(dòng)端中,用戶訪問了一個(gè)列表頁,上拉瀏覽列表頁的過程中,隨著滾動(dòng)高度逐漸增加,數(shù)據(jù)也將采用觸底分頁加載的形式逐步增加,列表頁瀏覽到某個(gè)位置,用戶看到了感興趣的項(xiàng)目,點(diǎn)擊查看其詳情,進(jìn)入詳情頁,從詳情頁退回列表頁時(shí),需要停留在離開列表頁時(shí)的瀏覽位置上,react中沒有現(xiàn)成得保留組件狀態(tài)得方法。
但是有第三方庫 react-activation 個(gè)人感覺這個(gè)好用!
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、安裝第三方庫
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、在需要保留狀態(tài)得組件上使用 KeepAlive 包裹
我要保留cate組件得狀態(tài)所以使用keepAlive包裹c(diǎn)ate組件
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
總結(jié)
到此這篇關(guān)于react實(shí)現(xiàn)組件狀態(tài)緩存的示例代碼的文章就介紹到這了,更多相關(guān)react 組件狀態(tài)緩存內(nèi)容請搜索以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持!
標(biāo)簽:
JavaScript
排行榜
