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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

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

作者:范德薩_ ? 更新時(shí)間: 2023-06-13 編程語(yǔ)言

前言

在移動(dòng)端中,用戶訪問(wèn)了一個(gè)列表頁(yè),上拉瀏覽列表頁(yè)的過(guò)程中,隨著滾動(dòng)高度逐漸增加,數(shù)據(jù)也將采用觸底分頁(yè)加載的形式逐步增加,列表頁(yè)瀏覽到某個(gè)位置,用戶看到了感興趣的項(xiàng)目,點(diǎn)擊查看其詳情,進(jìn)入詳情頁(yè),從詳情頁(yè)退回列表頁(yè)時(shí),需要停留在離開列表頁(yè)時(shí)的瀏覽位置上,react中沒有現(xiàn)成得保留組件狀態(tài)得方法。

但是有第三方庫(kù) react-activation 個(gè)人感覺這個(gè)好用!

提示:以下是本篇文章正文內(nèi)容,下面案例可供參考

一、安裝第三方庫(kù)

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é)

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

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