Usign react-router-dom,如何从React组件外部访问browserHistory对象?

Ale*_*roa 3 reactjs react-router redux react-redux react-router-dom

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

import {browserHistory} from 'react-router';
Run Code Online (Sandbox Code Playgroud)

从我的actionCreators文件中,我可以执行以下操作:

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

但是随着新的react-router-dom(v4)的出现,我似乎无法再像那样导入browserHistory,并且访问历史对象的唯一方法是从React组件props

this.props.history
Run Code Online (Sandbox Code Playgroud)

使用react-router-dom完成异步redux操作后,如何将用户重定向到新页面?

Tyl*_*nis 5

您正在寻找withRouter

“您可以通过withRouter高阶组件访问历史对象的属性和最接近的匹配项。”

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)
Run Code Online (Sandbox Code Playgroud)

  • 能够导入browserHistory并执行browserHistory.push('whereIWantToGo')变得非常简单和直接。v3和v4之间发生的一切似乎都是过度设计 (6认同)