2017-04-06 76 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

不錯。好工作。 –