5

使用以前的 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 components props

this.props.history

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

4

1 回答 1

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)
于 2017-04-06T04:04:37.207 回答