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

时间:2017-04-06 02:10:33

标签: reactjs redux react-router react-redux react-router-dom

使用之前的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组件道具

this.props.history

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

1 个答案:

答案 0 :(得分:4)

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)