反应路由器this.props.location

Анд*_*зюк 18 javascript reactjs react-router

我需要一个反应路由器v2 +的帮助我必须更改路由更改时的导航栏类例如 我route /profile className"profile-header"尝试this.props.location在导航栏组件中使用但它显示undefined

希望你的帮助

szy*_*onm 30

您的navbar组件(正如您在问题中描述的那样)可能不是路由组件,对吧?通过route component我的意思是你在使用一个react-router被加载特定路由配置.

this.props.location只有这样才能访问route component,所以你需要把它传递给你navbar.

我们来举个例子:

你的路由器配置:

<Router>
    <Route path="/" component={App}>
    // ...
</Router
Run Code Online (Sandbox Code Playgroud)

路线组件App:

class App extends React.Component{
  // ...
  render() {
    return <Navbar location={this.props.location}/>
  }
}
Run Code Online (Sandbox Code Playgroud)


var*_*ons 8

在某些情况下,您可能无法访问 props.location 以传递给导航组件。

举个例子 - 我们的项目中有一个 header 组件,它包含在路由开关中,使其可用于所有路由。

<Switch>
  <Fragment>
    <Header/>
    <Route path='..' component={...}/>
    <Route path='..' component={...}/>
  </Fragment>
</Switch>
Run Code Online (Sandbox Code Playgroud)

在上述场景中,无法将位置数据传递给 Header 组件。

当您的路由器未呈现组件时,更好的解决方案是使用 withRouter HOC。当您将它包装在 withRouter HOC 中时,您仍然可以访问路由器属性历史记录、匹配和位置:

import { withRouter } from 'react-router-dom'
.... 
....
export default withRouter(ThisComponent)
Run Code Online (Sandbox Code Playgroud)