【问题标题】:React router 4 not updating when using children prop on history.push在 history.push 上使用 children 道具时反应路由器 4 不更新
【发布时间】:2017-10-05 22:12:42
【问题描述】:

我有这段代码:

class Base extends Component {
  changeRoute = () => {
    // after this, address bar gets updated but I can't see the Users
    // component, only Home component.
    this.props.history.push('/users');
  }

  render() {
    return (
      <div>
        <MyBar />
        {this.props.children}
      </div>
    )
  }
}

class App extends Component {
  render() {
    return (
      <Router>
        <Base>
          <a onClick={this.changeRoute}>Change</a>
          <Route path="/home" component={Home} />
          <Route path="/users" component={Users} />
        </Base>
      </Router>
    )
  }
}

但是,当我尝试使用 history.push 或从 react-router-redux 推送来更改位置时,我可以看到浏览器路径已更新但内容未更新,它显示了原始路径内容。我还注意到,每当我刷新浏览器时,我都能看到与路径相关的正确内容。

当我将代码更改为以下内容时,浏览器路径和内容都会按预期相应更新,我的问题是:为什么它的行为不同?如果在我看来这两个代码都做同样的事情。

class Base extends Component {
  render() {
    return (
      <MyBar />
    )
  }
}

class App extends Component {
  changeRoute = () => {
    // after this, address bar and component are updated as expected.
    this.props.history.push('/users');
  }
  render() {
    return (
      <Router>
        <div>
          <Base />
          <a onClick={this.changeRoute}>Change</a>
          <Route path="/home" component={Home} />
          <Route path="/users" component={Users} />
        </div>
      </Router>
    )
  }
}

编辑: 我在源代码中添加了 push 方法。这是我用来导出 App 组件的一段代码:

import {withRouter} from 'react-router';

export default withRouter(App);

【问题讨论】:

  • 使用 withRouter 的 react-router-dom 像 withRouter(App)

标签: reactjs react-router


【解决方案1】:

这是我运行的代码,它运行良好。您能否检查一下我的代码是否需要更改以重现您的问题?

import React from 'react';
import ReactDOM from 'react-dom';
import {NavLink, BrowserRouter,Route} from 'react-router-dom';
class Base extends React.Component {
    render() {
      return (
        <div>
          <div>MyBar</div>
          {this.props.children}
        </div>
      )
    }
  }

  class App extends React.Component {
    render() {
      return (
        <BrowserRouter>
          <Base>
            <NavLink to="/users">Change</NavLink>
            <Route path="/home" render={()=>"Home"} />
            <Route path="/users" render={()=>"Users"} />
          </Base>
        </BrowserRouter>
      )
    }
  }

ReactDOM.render(<App />, document.getElementById('root'));

编辑:据我了解,您希望能够在单击更改链接时导航到用户页面。正确的方法是使用 NavLink 控件。这不需要使用 withRouter HOC,它只能在路由器组件内部使用,而不是在它外部。

【讨论】:

  • 嗨,谢谢。我刚刚更新了问题以显示我如何更改历史路径。问题出在点击“更改”链接时。
  • 当我运行您的代码时,我收到错误消息“您不应该在 之外使用 或 withRouter()”。 codesandbox.io/s/9j16n744mp
猜你喜欢
  • 2018-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-19
  • 1970-01-01
  • 1970-01-01
  • 2021-01-02
相关资源
最近更新 更多