分析说明:
可以通过 children 属性,回调函数的参数,拿到当前的路由信息。它提供了 match
属性,表示当前匹配的路由信息
- 如果匹配,match 中会给出当前匹配的路由信息
- 如果不匹配,match 为 null
因此,可以通过判断 match !== null
来判断当前路由是否匹配
<Route
children={(props.match) => {
console.log('当前路由是否匹配:', props.match)
}}
/>
注意:由于被缓存的路由永远都需要匹配,所以,应该将 KeepAlive 组件放在 Switch 组件外部!
步骤:
- 封装 KeepAlive 组件
- 使用 KeepAlive 组件来配置路由,缓存路由
核心代码:
components/KeepAlive/index.tsx 中:
import { Route, RouteProps } from 'react-router-dom'
// 使用方式:
/*
<KeepAlive path="/home">
<Layout />
</KeepAlive>
*/
export const KeepAlive = ({ children, ...rest }: RouteProps) => {
return (
<Route
{...rest}
children={props => {
const isMatch = props.match !== null
return (
<div
style={{
height: '100%',
display: isMatch ? 'block' : 'none'
}}
>
{children}
</div>
)
}}
/>
)
}
App.tsx 中:
// 在 Switch 外部使用 KeepAlive 组件
// Layout 组件的路由:
<KeepAlive path="/home">
<Layout></Layout>
</KeepAlive>
<Switch>
// ... 其他路由配置
</Switch>