使用 react-router-dom,如何从 React 组件外部访问浏览器历史记录对象?

Usign react-router-dom, how can I access browserHistory object from outside a React component?

使用之前的 react-router 我可以做到这一点:

import {browserHistory} from 'react-router';

从我的 actionCreators 文件中,我可以做这样的事情:

...some async action completed (for example, user logged in successfully)..
browserHistory.push('/dashboard');

但是使用新的 react-router-dom (v4) 似乎我不能再像那样导入 browserHistory 并且访问历史对象的唯一方法是来自 React 组件 props

this.props.history

使用 react-router-dom 完成异步 redux 操作后,将我的用户重定向到新页面的方法是什么?

withRouter 就是您要找的。

"You can get access to the history object’s properties and the closest 's match via the withRouter higher-order component."

import React, { PropTypes } from 'react'
import { withRouter } from 'react-router'

// A simple component that shows the pathname of the current location
class ShowTheLocation extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>You are now at {location.pathname}</div>
    )
  }
}

// Create a new component that is "connected" (to borrow redux
// terminology) to the router.
const ShowTheLocationWithRouter = withRouter(ShowTheLocation)