当前位置: 代码迷 >> 综合 >> withRouter() 在非路由组件中使用路由库的api
  详细解决方案

withRouter() 在非路由组件中使用路由库的api

热度:32   发布时间:2023-10-27 13:54:50.0

我们知道,在非路由组件中,是拿不到例如像  this.props.location.pathname 数据。

倘若我们想拿到类似这种路由数据,可以使用withRouter()将非路由组件包装成路由组件。用法与redux中的connect类似。

如下:

import React, {Component} from 'react'
import {withRouter} from 'react-router-dom'// 希望在非路由组件中使用路由库的api
// withRouter()
class NavFooter extends Component {render() {const path = this.props.location.pathname   // 只有路由组件才能访问location等。所以要用withRouter包装成路由组件return (<div>当前路由是{path}</div>)}
}
// 向外暴露withRouter()包装产生的组件
// 内部会向组件中传入一些路由组件特有的属性: history  location  math
export default withRouter(NavFooter)