1. Implementation based on react-route6 useOutlet
2. Code rendering
import React, { useRef, createContext, useContext } from 'react' import { useOutlet, useLocation, matchPath } from 'react-router-dom' import type { FC } from 'react' //Create a Context outside the componentexport const KeepAliveContext = createContext<KeepAliveLayoutProps>({ keepalive: [], keepElements: {} }) //Give page cache setting conditions judgmentconst isKeepPath = (aliveList: any[], path: string) => { let isKeep = false (item => { if (item === path) { isKeep = true } if (item instanceof RegExp && (path)) { isKeep = true } }) return isKeep } //Judge whether the current page has been cached. If it is, control the hidden switch to display. If it is not, it will render normally.export function useKeepOutlets() { const location = useLocation() const element = useOutlet() const { keepElements, keepalive } = useContext<any>(KeepAliveContext) const isKeep = isKeepPath(keepalive, ) if (isKeep) { [] = element } //Show and hide tags return <> { ().map(([pathname, element]: any) => ( <div key={pathname} style={{ height: '100%', width: '100%', position: 'relative', overflow: 'hidden auto' }} className="rumtime-keep-alive-layout" hidden={!matchPath(, pathname)}> {element} </div> )) } <div hidden={isKeep} style={{ height: '100%', width: '100%', position: 'relative', overflow: 'hidden auto' }} className="rumtime-keep-alive-layout-no"> {!isKeep && element} </div> </> } //Set the common component typeinterface KeepAliveLayoutProps { keepalive: any[] keepElements?: any dropByCacheKey?: (path: string) => void } //Encapsulate common componentsconst KeepAliveLayout: FC<KeepAliveLayoutProps> = (props) => { const { keepalive, ...other } = props const keepElements = <any>({}) function dropByCacheKey(path: string) { [path] = null } return (< value={{ keepalive, keepElements, dropByCacheKey }} {...other} />) } export default KeepAliveLayout
Code Analysis
isKeepPath
Configure keepalive to support strings and regularities, and use it to determine whether the current page needs to be maintained, because if the entire project page remains state, it will consume a lot of performance.
Parameter 1 is an array composed of cacheable paths or regular expressions, and parameter 2 is the current path.
If the current path is in the cached path array or its path conforms to the regular expression, isKeep is true, otherwise false
useKeepOutlets
Make a page DOM by determining whether the current page is a page that needs to be maintainedhidden
The visible switch.
It should be noted that all pages maintained by the specified state will be mounted on the page DOM tree after the first rendering, just for use.!matchPath(, pathname)
Controls visible and hidden.
Pages that are not maintained in the specified state are used{!isKeep && element}
Control, go through the normal life cycle of React components.
location
Current path information
element
Get the current routing component, that is, the nested routing component under the current configuration
useContext<any>(KeepAliveContext)
Getting properties in Context objects through the useContext() hook function has facilitated sharing of state among components
isKeep
Use the page cache setting conditions to determine whether the current path is a cached path. If the conditions are met and isKeep is true, then the current routing component is bound to the keepElements Ref with the current component path name as the attribute name.
describe:()
Returns an array whose elements are directly inobject
The array corresponding to the enumerable attribute key value pairs found on. The order of properties is the same as given by manually looping the property values of the object.
Enumerable: The function of enumerable is similar toLiteral type + union type combinationThe function of the
Parameters: Objects that can return key-value pairs of their enumerable properties
Return value: an array of key-value pairs of the given object itself enumerable attributes
key
Keep the key unchanged and the repaint of React will not be triggered
hidden
Control display and hidden switches
matchPath(, pathname)}
All pages that are maintained in the specified state will be mounted on the page DOM tree after the first rendering, just for use.!matchPath(, pathname)
Control display is hidden.
//matchPath: Parameter 1 is the current path, parameter 2 is the cache path, determine whether the current route path matches the cache path
Pages that are not maintained in the specified state are used{!isKeep && element}
Control, go through the normal life cycle of React components
KeepAliveLayout
Components exposed after packaging
FC
It is a functional component, a generic used under TypeScript, the full name is
,
<>
Specified attribute types can be detected
keepElements
use<any>({})
If the nodes that are used to save page data is because our context is not re-renderedkeepElements
It will not be reset, which is equivalent tokey
dropByCacheKey
dropByCacheKey is a function to clear cache, destroying the component by controlling the ref of the current component to destroy the component
other
const { keepalive, ...other } = props
Chinese...other is other configuration, here we can directly traverse inheritance
Provider
(< value={{ keepalive, keepElements, dropByCacheKey }} {...other} />)
principle:
Each Context object returns a Provider React component that allows consuming components to subscribe to changes in context.
Provider receives onevalue
Properties, passed to the consumer component. A Provider can correspond to multiple consumer components. Multiple providers can also be used in nesting, and the inner layer will cover the outer layer of data.
When Provider'svalue
When the value changes, all consumer components inside it will be re-rendered
III. Use
import KeepAliveLayout, { useKeepOutlets, KeepAliveContext }from'@/components/KeepAliveLayout' import { useLocation } from 'react-router-dom' import React, { useState, useContext } from 'react' // Use useKeepOutlets in KeepAliveLayout to get the content of the currently rendered pageconst Layout = () => { const element = useKeepOutlets() return ( {element} ) } // Use KeepAliveLayout to wrap the contextconst App = () => { return ( <KeepAliveLayout keepalive={[/./]}>//It is impossible for all components to cache, so you need to set cache conditions, pass cacheable paths or regular expressions // App </KeepAliveLayout> ); } // Use useContext to get dropByCacheKey to clear the cacheconst Home = () => { const { dropByCacheKey } = useContext<any>(KeepAliveContext); const { pathname } = useLocation(); return ( <button onClick={() => dropByCacheKey(pathname)}>Clear cache</button> ) }
This is the end of this article about React-Route6's keep-alive effect. For more related React-Route6 keep-alive content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!