react中封装一个简单的keep-alive组件

分析说明

参考:React 路由 match 属性

可以通过 children 属性,回调函数的参数,拿到当前的路由信息。它提供了 match 属性,表示当前匹配的路由信息

  • 如果匹配,match 中会给出当前匹配的路由信息
  • 如果不匹配,match 为 null

因此,可以通过判断 match !== null 来判断当前路由是否匹配

<Route
  children={(props.match) => {
    console.log('当前路由是否匹配:', props.match)
  }}
/>

注意:由于被缓存的路由永远都需要匹配,所以,应该将 KeepAlive 组件放在 Switch 组件外部!

步骤

  1. 封装 KeepAlive 组件
  2. 使用 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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值