react路由在layout中的监听

  • 业务中需要在layout里来监听路由的变化,但是layout并不是一个路由组件,所以layout组件内的props并没有location,history等属性,(路由组件:由Route组件处理的才是路由组件)所以我们需要将layout组件转变成路由组件,react-route-dom提供的高阶组件(withRouter)可以实现,

withRotuer 的用法:他是一个函数,接受一个组件作为参数

withRouter 是一个高阶组件 HOC ,因为默认只有被 Route 包裹的组件才能获取到路由状态,如果当前非路由组件想要获取状态,那么可以通过 withRouter 包裹来获取 history ,location 等信息。

const Nav = (props) => {
useEffect(()=>{
    console.log('history.location.pathname:', history.location)
  },[history.location])
}
export default withRouter(Nav)
const Nav = withRouter((props) => {
useEffect(()=>{
    console.log('history.location.pathname:', history.location)
  },[history.location])
})
export default Nav
  • 也可以通过 history 对象来进行监听。
    • history.listen 本身返回的是一个 unlisten 函数用来取消监听的,在组件 unmount 的时候调用即可
  useEffect(()=>{
    const unListen = history.listen((location)=>{
      console.log('2222:', location)
    })
    return unListen
  },[])

参考文档:「React进阶」react-router v6 通关指南 - 掘金

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值