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

IT技术 reactjs redux react-router react-redux react-router-dom
2021-05-04 08:04:32

使用以前的 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 操作后,将我的用户重定向到新页面的方法是什么?

1个回答

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)