首页 文章

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

提问于
浏览
2

使用之前的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 回答

  • 3

    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)
    

相关问题