In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use react-activation to support keepAlive support to return parameters". In daily operation, I believe many people have doubts about how to use react-activation to support keepAlive support to return parameters. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the questions of "how to use react-activation to support return parameters". Next, please follow the editor to study!
Introduction
This project is a mall background management system, built with umi2.0, state management using dva, want to achieve a similar effect of vue keep-alive.
The specific manifestations are as follows:
Jump from list page A to the details page of A, list page A cache
The details page did not do anything, jump back to list page A, list page A does not refresh, list page A page number remains unchanged
The details page has been edited, jump back to list page A, the list page An is refreshed, and the list page A number remains unchanged.
Create a new operation on the details page, jump back to list page A, refresh list page A, and change the number of list page A to 1
Jump from list page A to list page B, which is not cached
The summary is that a page is cached only when it jumps to a specified page, and when the cached page is returned, you can control whether it is refreshed or not.
Code 1. Install react-activation "react-activation": "^ 0.10.2", 2. Add meta to the route
This project uses centralized configuration routing. I added the meta attribute. The presence of meta.keepAlive indicates that this is a route that needs to be keepAlive. Meta.keepAlive.toPath means that only when going to this route, cache is needed.
Const routes = [. {name: 'commodity management (Mall goods)', path:'/ web/supplier/goods/mallgoodsmgr', component:'. / supplier/goods/goodsManage', meta: {keepAlive: {toPath:'/ web/supplier/goods/mallgoodsmgr/detail' / / only when you go to the details page, you need to cache the route of merchandise management (Mall merchandise). 3. Render in the root component
In the root component, you wrap the entire application and the pages that need to be cached. This part of the document is written in, and if it is umi, it can be written in layouts.
Get all the routes:keepAliveRoutes with meta.keepAlive through the flattening calculation of tree, and judge by location.pathname that if the current page needs keepAlive, then you need to use a package.
Import KeepAlive, {AliveScope, useAliveController} from 'react-activation'// tree flattening function treeToList (tree ChildrenKey = 'routes') {var queen = [] var out = [] queen = queen.concat (tree) while (queen.length) {var first = queen.shift () if (first [childrenKey]) {queen = queen.concat (First [childr enKey]) delete first [childrenKey]} out.push (first)} return out} / / from routes routing tree Get all meta.keepAlive routes: keepAliveRoutesconst allFlatRoutes = treeToList (routes) / / all routes const keepAliveRoutes = allFlatRoutes.filter ((item) = > item.meta?.keepAlive) / / keepAlive routes function Index (props) {const location = useLocation () const routeItem = keepAliveRoutes.find ((item) = > item.path = = location.pathname) / / from page let dom = props.children if (routeItem) {dom = {props.children} / / Id must be added, otherwise keepAlive's page will jump to another keepAlive's page will have a problem} return ({dom})}
Note that if the AliveScope contains more than one KeepAlive, be sure to bring id.
4. Cache only when you jump to the specified page
After the previous step, the page is cached, but any page it jumps will be cached, and we need to cache it only when we jump to the specified page.
My method is
If the page you jump to happens to be its own meta.keepAlive.toPath, do nothing (because the page is already wrapped in KeepAlive and is in a cached state)
If it is not its own meta.keepAlive.toPath, call the clear method to clear the cache
4.1 clear method
React-activation provides useAliveController to manually control the cache, where the clear method is used to clear KeepAlive in all caches.
4.2 recording toPath with state management
Monitor history and record the upcoming page (next page) toPath with status management (dva I use)
I record the pages that the app is about to visit through dva
Const GlobalModel = {namespace: 'global', state: {/ * keepAlive * / toPath:', keepAliveOptions: {}, / / options}, effects: {}, reducers: {save (state, {payload}) {return {... state,... payload,}}, setToPath (state) {payload}) {return {... state, toPath: payload,}},}, subscriptions: {setup ({history, dispatch}) {/ / Subscribe history (url) change, trigger `load`action if pathname is `/ `history.listen ((route, typeStr) = > {const {pathname} = route dispatch ({type: 'setToPath', payload: pathname) })}),},}
4.3 add useEffect to the root component
The root component reads the toPath of the page to be visited from dva, and then adds a useEffect. If the page to be visited is not its own meta.keepAlive.toPath, it executes the clear method provided by react-activation.
.. function Index (props) {const location = useLocation () const toPath = props.global.toPath / / get the page to be visited from dva const routeItem = keepAliveRoutes.find ((item) = > item.path = = location.pathname) / / from page / add code useEffect () = > {console.log ('toPath change') ToPath) / / from page is the page that needs keepAlive if (routeItem) {console.log ('from page is the page that needs keepAlive', routeItem) if (toPath = = routeItem.meta?.keepAlive.toPath) {/ / the page you go to happens to be the keepAlive.toPath console.log of the current route ('the page you go to happens to be the keepAlive.toPath of the current route Else {console.log ('clear') if (aliveController?.clear) {aliveController.clear ()} [toPath]) / / the new code end let dom = props.children if (routeItem) {dom = {props.children} / / id must be added, otherwise the page of keepAlive will jump to another keepAlive page will have a problem} return ({dom})} export default connect (({global, login}) = > ({global, login})) (Index)
4.4 Optimization
Now there is a problem: when you jump to the details page from list A, then to list B, and then to list A, A does not refresh:
List A = > details page = > list B = > list A. list An is not refreshed or blank at this time.
Because when we came out of the details page (jump to list B), we did not empty the cache of list A.
So to check whether the current page is a toPath page that needs a keepAlive page
Root component:
Function Index () {... Const parentItem = keepAliveRoutes.find ((item) = > item.meta?.keepAlive?.toPath = = location.pathname) / / parentItem exists toPath useEffect (()) = > {console.log ('toPath change') indicating that the current page is a keepAlive. ToPath)... / / newly added code / / from page is the toPath if (parentItem) {console.log of a keepAlive page ('from page is the toPath of a keepAlive page ParentItem', parentItem) if (toPath = = parentItem.path) {/ / the page you went to is parentItem.path console.log ('the page you went to is parentItem.path Do nothing')} else {console.log ('clear') if (aliveController?.clear) {aliveController.clear ()}, [toPath]).} 5, extract logic to custom hooks
UseKeepAliveLayout.js
Import {useEffect} from 'react'import {useLocation} from' react-router-dom'import KeepAlive, {AliveScope, useAliveController} from 'react-activation'import routes from'.. /.. / config/router.config'// tree flattening function treeToList (tree ChildrenKey = 'routes') {var queen = [] var out = [] queen = queen.concat (tree) while (queen.length) {var first = queen.shift () if (first [childrenKey]) {queen = queen.concat (firstchildr enKey]) delete first [childrenKey]} out.push (first)} return out} const allFlatRoutes = treeToList (routes) / / all routes const keepAliveRoutes = allFlatRoutes.filter ( (item) = > item.meta?.keepAlive) / / routing function index (props) {const location = useLocation () / / keep alive const aliveController = useAliveController () const toPath = props.global.toPath / / Page to be visited const routeItem = keepAliveRoutes.find ((item) = > item.path = = location.pathname) / / from Page const parentItem = keepAliveRoutes.find ((item) = > item.meta?.keepAlive?.toPath = = location.pathname) useEffect (() = > {console.log ('toPath change' ToPath) / / from page is the page that needs keepAlive if (routeItem) {console.log ('from page is the page that needs keepAlive', routeItem) if (toPath = = routeItem.meta?.keepAlive.toPath) {/ / the page you go to happens to be the keepAlive.toPath console.log of the current route ('the page you go to happens to be the keepAlive.toPath of the current route Do nothing')} else {console.log ('clear') if (aliveController?.clear) {aliveController.clear ()}} / / the from page is the toPath if (parentItem) {console.log (' from page is the toPath of a keepAlive page) of a keepAlive page. ParentItem', parentItem) if (toPath = = parentItem.path) {/ / the page you went to is parentItem.path console.log ('the page you went to is parentItem.path Nothing')} else {console.log ('clear') if (aliveController?.clear) {aliveController.clear ()}, [toPath]) return {fromIsNeedKeepAlive: routeItem,}} export default index
The root component only needs to introduce this hooks:
Function Index (props) {const location = useLocation () const {fromIsNeedKeepAlive} = useKeepAliveLayout (props) / / key code let dom = props.children if (fromIsNeedKeepAlive) {dom = {props.children} / / id must be added otherwise the page of keepAlive jumps to another keepAlive's page will have problems} return ({dom})} 6, when returning to the list page from the details page Controls whether the list page is refreshed, that is, parameters are returned
Now there is only one last question left, which is actually the problem of passing parameters on the page of keepAlive and goBack.
Train of thought:
Add a keepAliveOptions object to the state management, which is the parameter that the details page passes to the list page
When the details page executes goBack, call the status management dispatch to modify the keepAliveOptions
The list page listens to the keepAliveOptions and executes the incoming method if the keepAliveOptions changes
UseKeepAliveOptions.js
Import {useEffect} from 'react'import {useDispatch, useStore} from' dva'import {router} from 'umi'/** * @ description keepAlive page, when a parameter is passed You can use this monitor to listen to * @ param {(options:object) = > void} func * / export function useKeepAlivePageShow (func) {const dispatch = useDispatch () const store = useStore () const state = store.getState () const options = state.global.keepAliveOptions?? {} useEffect (() = > {func (options) / / execute return () = > {console.log ('cache unloading of keepAlive pages') dispatch ( {type: 'global/save' Payload: {keepAliveOptions: {}, [JSON.stringify (options)])} / * * @ description PageA (page of keepAlive) went to PageB When you want to pass parameters to PageA from PageB goBack, you need to use this method * @ returns {(params:object) = > void} * / export function useKeepAliveGoback () {const dispatch = useDispatch () function goBack (parmas = {}) {dispatch ({type: 'global/save', payload: {keepAliveOptions: parmas,},}) router.goBack ()} return goBack}:
Details page
Import {useKeepAliveGoback} from'@ / hooks/useKeepAliveOptions'function Index () {... Const keepAliveGoback = useKeepAliveGoback () / / is used to pass parameters to the page of the previous keepAlive. Return (. {keepAliveGoback ({isAddSuccess: true}) / / pass options} > to the list page.)}
List page
Import {useKeepAlivePageShow} from'@ / hooks/useKeepAliveOptions'function Index () {... / / options: isAddSuccess isEditSuccess useKeepAlivePageShow ((options) = > {console.log ('keepAlive options') Options) if (options.isAddSuccess) {/ / newly created successfully / / list page number becomes 1 and refresh search ()} else if (options.isEditSuccess) {/ / edited successfully / / list page number remains unchanged and refresh getData ()}). Return.} at this point, the study on "how to use react-activation to support keepAlive support to return parameters" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.