我刚刚把react-router从v3替换为v4。 但我不确定如何以编程方式在组件的成员函数中导航。 即在handleClick()函数中,我想在处理一些数据后导航到/path/some/where。 我以前是这样做的:

import { browserHistory } from 'react-router'
browserHistory.push('/path/some/where')

但是我在v4中找不到这样的界面。 如何使用v4导航?


当前回答

由于没有其他方法来处理这个可怕的设计,所以我编写了一个使用withRouter HOC方法的通用组件。下面的例子是包装一个按钮元素,但你可以更改为任何你需要的可点击元素:

import React from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router-dom';

const NavButton = (props) => (
  <Button onClick={() => props.history.push(props.to)}>
    {props.children}
  </Button>
);

NavButton.propTypes = {
  history: PropTypes.shape({
    push: PropTypes.func.isRequired
  }),
  to: PropTypes.string.isRequired
};

export default withRouter(NavButton);

用法:

<NavButton to="/somewhere">Click me</NavButton>

其他回答

第一步:只需要在上面导入一个东西:

import {Route} from 'react-router-dom';

第二步:在Route中,传递历史记录:

<Route
  exact
  path='/posts/add'
  render={({history}) => (
    <PostAdd history={history} />
  )}
/>

第三步:历史被接受为下一个组件的道具的一部分,所以你可以简单地:

this.props.history.push('/');

这很简单,也很有力。

你也可以简单地使用props来访问历史对象:

我认为@rgommezz涵盖了大多数情况,除了一个我认为非常重要的情况。

// history is already a dependency or React Router, but if don't have it then try npm install save-dev history

import createHistory from "history/createBrowserHistory"

// in your function then call add the below 
const history = createHistory();
// Use push, replace, and go to navigate around.
history.push("/home");

这允许我写一个简单的服务与动作/调用,我可以调用从任何组件做导航,而不需要在我的组件上做很多HoC…

目前还不清楚为什么以前没有人提供这种解决方案。我希望它能有所帮助,如果你看到任何问题,请告诉我。

因为有时我更喜欢通过应用程序切换路由,然后通过按钮,这是一个最小的工作示例,对我有用:

import { Component } from 'react'
import { BrowserRouter as Router, Link } from 'react-router-dom'

class App extends Component {
  constructor(props) {
    super(props)

    /** @type BrowserRouter */
    this.router = undefined
  }

  async handleSignFormSubmit() {
    await magic()
    this.router.history.push('/')
  }

  render() {
    return (
      <Router ref={ el => this.router = el }>
        <Link to="/signin">Sign in</Link>
        <Route path="/signin" exact={true} render={() => (
          <SignPage onFormSubmit={ this.handleSignFormSubmit } />
        )} />
      </Router>
    )
  }
}

最简单的方法是:

this.props.history.push(“/new/url”)

注意:

如果历史道具不可用,你可以将它从父组件传递到你想调用该动作的组件。