react利用react-activation实现子路由缓存

1.下载依赖

yarn add react-activation

2.父路由里的代码

import React, { FunctionComponent,cloneElement } from 'react'
import Styles from './layout.less'
import { IRouteComponentProps } from 'umi'
import { Switch, Route } from 'react-router';
import KeepAlive, { AliveScope } from 'react-activation'

// 需要缓存的路由
const KEEP_ALIVE_ROUTES = [
    '/reactaction/rca'
]

const ReactAction: FunctionComponent<IRouteComponentProps> = ({ children, history, location }) => {
    return (
        <div className={Styles.layout}>
            <div className={Styles.layout_page}>
                <AliveScope>
                    <Switch location={location}>
                        {
                            children.props.children.map((route: any) => {
                                return KEEP_ALIVE_ROUTES.includes(route.props.path) ?
                                    <Route key={route.props.path} path={route.props.path} render={() =>
                                        <KeepAlive saveScrollPosition={`screen`}>{children}</KeepAlive>}
                                    ></Route> :
                                    cloneElement(route, { key: route.props.path })
                            })
                        }
                    </Switch>
                </AliveScope>
            </div>
            <div className={Styles.layout_bar}>
                <button onClick={() => history.push('/reactaction/rca')}>缓存页面</button>
                <button onClick={() => history.push('/reactaction/rcb')}>非缓存页面1</button>
                <button onClick={() => history.push('/reactaction/rcc')}>非缓存页面2</button>
            </div>
        </div>
    )
}

export default ReactAction

你可能感兴趣的:(react.js,缓存,javascript)