【问题标题】:React Router this.props.location is always Undefined反应路由器 this.props.location 总是未定义
【发布时间】:2019-12-10 20:26:45
【问题描述】:

我需要为当前路径的名称设置一个类名,例如“inventory”或“about”。但是,当我尝试使用 this.props.location 时,它始终是未定义的。有人可以向我解释为什么会这样吗?

class Header extends Component{
    render(){
      return(
        <Router>
          <div className={'header ' + this.props.location}>
            <div className="header-content">        
                <div className="header-right">
                <NavLink exact to="/">Home</NavLink>
                <NavLink to="/about">About</NavLink>
                <NavLink to="/inventory">Inventory</NavLink>
                </div>
            </div>
          </div>
          <div className="page-content">

            <Route exact path="/" component={Home}/>
            <Route path="/about" component={About}/>
            <Route path="/inventory" component={Inventory}/>
          </div>
        </Router>
      );
    }
}

【问题讨论】:

标签: javascript reactjs react-router


【解决方案1】:

这里的问题是historylocation 和 blah blah blah 已被 inyected 到 &lt;Route /&gt; 中的组件,但您正试图从创建路由器的同一组件访问它。因此,或者您在当前的父文件中创建了路由器,或者改为使用窗口对象

 <div className={'header ' + window.location}>

【讨论】:

    【解决方案2】:

    我认为您应该将路由器在层次结构中移到更高的位置,理想情况下移至呈现您的 App 组件的组件,如下所示:

    <Router history={history}>
        <App />
    </Router>
    

    您当前正在尝试从 props 中读取位置,但由于您在同一个组件中渲染 Router,它无法将位置传递给 props,因此它将始终为空。 如果您通过路由器包装您的应用程序,您可以将位置道具向下传递到需要它的任何其他组件(例如 Header)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-02
      • 1970-01-01
      • 1970-01-01
      • 2016-04-08
      • 1970-01-01
      • 2017-12-21
      • 2018-05-16
      • 2017-05-18
      相关资源
      最近更新 更多