【问题标题】:withRouter Does Not passes Route props to componentwithRouter 不会将 Route 道具传递给组件
【发布时间】:2019-01-05 11:58:38
【问题描述】:

这是我的导航组件:

import React from 'react'

class Navigation extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      type: 'signUp', // or login
      showModal: false,
      isLoggedIn: false,
    }
  }

  ...some code

  render() {

    const { showModal, type, isLoggedIn } = this.state

    console.log(this.props.location); // all problem is this, I'm not getting it in console

    return(
      ...some more code
    )
  }
}

export default withRouter(Navigation)

这是它在 app.js 中使用的地方

class App extends React.Component {

  render () {
    return(
      <Router>
          <Fragment>

            <Navigation /> // <= right there

            <Switch>
              <Route exact path='/' component={HomePage}/>
              <Route exact path='/search' component={HomePage}/>
              <Route component={Lost} />
            </Switch>
          </Fragment>
      </Router>
    )
  }
}

我想在我的 &lt;Navigation /&gt; 组件中获得更新的路由道具,例如 matchlocationhistory 但是我只有在组件第一次安装在 DOM 上时才得到它,在我的其他组件中,我使用window.history.pushState 更新路由,但在浏览器中的链接更新后,我无法从 withRouter 获取路由道具。

我用window.history.pushState 更新路线,因为:

  1. 我找不到任何方法来更新地址栏中的链接而不显示用户或使用 React 路由器 DOM 将用户重定向到新组件(我这样做是否正确?)

  2. 基于此,我然后使用window.location.pathname 为某些组件添加一些特定的样式)

另外,我阅读了thisthis 的全部内容,但我无法解决这个问题。我做错了什么?

【问题讨论】:

    标签: javascript reactjs react-router browser-history


    【解决方案1】:

    withRouter 为您提供最接近&lt;Route&gt; 的路由道具,并且由于Navigation 组件不在Route 内,您将无法获得route props

    你可以例如将Navigation 组件放在始终可见的Route 之外的Route 上。

    示例

    class App extends React.Component {
      render() {
        return (
          <Router>
            <Fragment>
              <Route path="/" component={Navigation} />
              <Switch>
                <Route exact path="/" component={HomePage} />
                <Route exact path="/search" component={HomePage} />
                <Route component={Lost} />
              </Switch>
            </Fragment>
          </Router>
        );
      }
    }
    

    【讨论】:

    • 多么有趣和伟大的用法。我以前从未见过这种情况。谢谢@Tholle,注意到了。
    • 我应用了你的方法,但我意识到,由于通过 window.history.pushState 添加新的链接路径,react 将检查导航组件的更改,但等待导航组件没有任何更改,所以它会不会重新渲染导航组件以在其上应用路由道具,尽管如此,我仍然无法在导航组件中获取路由道具....
    • @a_m_dev 我不太确定我是否理解。你为什么使用window.history.pushState 而不是this.props.history.push?你不想使用 React Router 的功能吗?
    • 是的,b/c 我注意到了我的原因,我找不到任何合适的方法来仅更新链接而不是更新链接并使用反应路由器显示新组件...
    • @a_m_dev 对不起,我不明白你在说什么。我不明白您为什么要更改 URL 但不更改 Route 的活动状态。
    猜你喜欢
    • 2019-05-13
    • 2018-09-12
    • 2020-01-17
    • 2019-07-29
    • 2018-07-07
    • 1970-01-01
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多