2017-04-15 108 views
1

需要與重定向幫助在action.js推歷史反應路由器V4沒有導航

import axios from "axios"; 
import createHistory from 'history/createBrowserHistory'; 
import {Notification} from "modules/shared/components"; 
import * as types from "./actionTypes"; 
import {API_URL} from "utils/constants"; 

const history = createHistory(); 
export function signUp({name, email, password}) { 
    return (dispatch) => { 
     dispatch({type: types.AUTH_REQUEST}); 

     axios.post(`${API_URL}/auth/register`, {name, email, password}) 
      .then(response => { 
       history.push('/'); 
      }) 
      .catch(error => { 
       const {title, message} = error; 
       dispatch(Notification('error', title, message)); 
       dispatch({type: types.AUTH_ERROR, payload: error}); 
      }) 
    } 
} 

在過去,我可以用browserHistory.push('/'),它將我重定向到/。使用React Router v4 browserHistory func後,我用createHistory更改了它。是的它的工作,但它只是改變我的網址,永遠不會將我重定向到網址。

任何解決方案?

回答

6

在反應路由器V3,browserHistory是單身,你可以用它隨時隨地瀏覽到一個特定的路線。但在第4版中,這不會起作用,因爲<BrowserRouter>會創建自己的歷史記錄實例。因此,您應該始終在有權訪問路由器實例的組件中更改路由。

下面是我在這種場景中使用的方法。您可以在axios成功回調中調用AUTH_SUCCESS動作,而將響應作爲您的動作負載,而不是嘗試在動作創建者內部導航。然後讓你的減速器根據這個動作改變狀態。舉一個例子,假設你的reducer在你的狀態下改變了user屬性,如下所示。

case types.AUTH_SUCCESS: 
     return Object.assign({}, state, { 
     user: action.user, 
     }); 

此外,您SignUp組件(或任何你調用signUp方法的組件)應該已經連接到user屬性的狀態爲道具。如果您使用的是reduxreact-redux,它可能是這樣的。

function mapStateToProps(state) { 
    return { 
    user: state.user 
    }; 
} 

export default connect(mapStateToProps)(SignUp); 

現在,當user變化signUp方法的結果,註冊部件將接收user作爲新的道具。因此,如果定義了user道具,則可以使用組件的componentWillReceiveProps方法更改路線。

componentWillReceiveProps(newProps){ 
if(newProps.user){ 
    this.props.history.push('/') 
} 
} 

爲了讓路由器的history實例作爲道具,無論是註冊組件應該已經呈現與Route或包裹withRouter

或者作爲替代,你可以按照如下的渲染方法使用新<Redirect/>組件。

render(){ 
    return this.props.user ? (<Redirect to="/" />) : (...your current JSX code for SignUp component); 
}