久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

react實(shí)現(xiàn)組件狀態(tài)緩存的示例代碼

瀏覽:168日期:2022-06-01 17:55:59
目錄
  • 前言
  • 一、安裝第三方庫
  • 二、配置操作
  • 總結(jié)

前言

在移動端中,用戶訪問了一個(gè)列表頁,上拉瀏覽列表頁的過程中,隨著滾動高度逐漸增加,數(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
主站蜘蛛池模板: 息烽县| 富顺县| 永德县| 汉中市| 班戈县| 绍兴县| 娱乐| 南城县| 桃源县| 旅游| 汤原县| 南和县| 遂川县| 师宗县| 安乡县| 兴仁县| 靖远县| 兴国县| 双辽市| 兖州市| 梁山县| 汝城县| 合作市| 磐石市| 洪泽县| 塘沽区| 康马县| 南宫市| 定边县| 原平市| 临潭县| 兴山县| 抚顺县| 蕉岭县| 海口市| 兴义市| 米易县| 鹿邑县| 康马县| 东台市| 育儿|