如何使用 react-router-v4 手动触发路由更改,就像 <Link> 那样,但在函数内部手动触发?

How to trigger manually a change of the route, with react-router-v4, like <Link> do it, but manually inside a function?

我正在使用 Reactreact-router-v4 进行项目,并且 我正在尝试找到一种手动触发路线更改的方法。

类似 <Link to="/newpage"> 的组件,它会将您带到新路线。

但我想从我的一种方法中手动完成,

类似于this.router.location = "/newpage"

使用withRouter高阶组件呢?

https://reacttraining.com/react-router/web/api/withRouter

class GoToNewPageButton extends React.Component {
  navigateToNewPage() {
    this.props.history.push('/newpage');
  }

  render() {
    return <button onClick={this.navigateToNewPage.bind(this)}>To the new page!</button>
  }
}

const GoToNewPageWithHistory = withRouter(GoToNewPageButton);

使用<Link>组件或withRouter高阶组件暴露的this.props.history.push方法,如上面回答中提到的PompolutZ。

这样的例子是<button onClick={() => this.props.history.push('/Home') } />

呈现将导航到新位置的重定向组件。

<Redirect to="/somewhere/else"/>

有关详细信息,请查看 documentation here.