2017-04-06 78 views
1

与以往的反应,路由器,我能够做到这一点:Usign react-router-dom,我如何从React组件外部访问browserHistory对象?

import {browserHistory} from 'react-router'; 

从我actionCreators文件,我可以做这样的事情:

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

但随着新反应路由器-DOM (V4)好像我不能再导入browserHistory就这样和访问历史记录对象的唯一方法是从反应的组分道具

this.props.history 

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

回答

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) 
+0

但是如果我想使用redux-thunk或redux-saga中的历史对象怎么办?不在反应组件内 –

+0

因此,最终我做的是在异步操作完成时将redux状态属性更改为true(让其称为“userLogged”)。我在“withRouter”和“componentWillReceiveProps”方法中封装了我的容器组件,我检查“userLogged”属性是否为true,然后使用历史对象推送新路线。 –

+0

不错。好工作。 –