日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

react實現組件狀態緩存的示例代碼_React

作者:范德薩_ ? 更新時間: 2023-06-13 編程語言

前言

在移動端中,用戶訪問了一個列表頁,上拉瀏覽列表頁的過程中,隨著滾動高度逐漸增加,數據也將采用觸底分頁加載的形式逐步增加,列表頁瀏覽到某個位置,用戶看到了感興趣的項目,點擊查看其詳情,進入詳情頁,從詳情頁退回列表頁時,需要停留在離開列表頁時的瀏覽位置上,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

總結

原文鏈接:https://blog.csdn.net/weixin_61102579/article/details/128836868

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新