2016-04-27 70 views
1

在我的React/Redux應用程序中,我有一些異步操作。 比方說,用戶發起一個getData請求到服務器。正在發送GET_DATA_REQUEST,並且AJAX呼叫正在前往服務器。Redux - 發送異步操作時更改URL

成功或失敗後,會相應地調度GET_DATA_SUCCESSGET_DATA_FAILURE操作,並將數據呈現給用戶界面。

現在,我希望我的應用程序能夠將歷史狀態(使用react-router-redux)作爲對AJAX回調的反應。意思是,成功後,用戶被「重定向到」另一個URL(路由),顯示的是不同的模塊,這取決於新接收的數據。

我意識到這是一個非常糟糕的想法在reducer中具有此功能,因爲它不會再純淨(URL更改是副作用)。

有什麼想法?

謝謝

+0

我在這裏的答案可能會幫助你:http://stackoverflow.com/a/36269830/728013 - 它將重定向邏輯放入你的動作中,讓你的減速器保持功能。 – bonesbrigade

回答

4

我相信這是處理您的情況的好方法。

首先,您應該在減速器中添加一個新屬性,以確定是否要重定向。

像這樣的事情

const initialState = { 
    ... 
    redirect : false // You could use a String with the new url instead of true/false 
    .... 
} 

switch ... 
case GET_DATA_SUCCESS: 
     return { 
      ...state, 
      redirect:true, 
     } 
case GET_DATA_FAILURE; 
     return { 
      ...state, 
      redirect:false 
     } 

然後,在連接到減速組件,你應該檢查在componentDidUpdate功能「重定向」的價值。

componentDidUpdate(){ 
     let {redirect} = this.props.yourReducerState; 
     if(redirect === true){ 
      this.context.router.push("new-url"); 
     } 
    } 

最後,你應該重置 「重定向」 上componentWillUnmount

希望它能幫助!

3

另一個很好的方法來做到這一點。我從this Udemy course瞭解到,我100%推薦它。

在組件(一個你想要提交的表單)中,把這個表單提交事件處理程序,它將調用該操作。

onSumbit(values) { 
    this.props.xxxActionCreator(() => { 
     this.props.history.push("/");//history is provided by react-route, .push("/") will direct app back to root path. 
    }); 
} 

render() { 
    <form onSumbit={this.onSumbit.bind(this)} > 
    .... </form> 

裏面的動作的創造者,把這個

export default function xxxAction(callback) { 
    const request = axios.get('...url').then(() => callback()); //here the function (callback) that was passed into this.props.xxxActionCreator() will be invoked. 
    //.then() is provided by promise. This line of code means the callback (which redirects you to the root path) will be invoked, once the promise (async) is resolved. 

    return { type: SOME_ACTION, payload: XXX }; 

GitHub demo在這裏你可以找到相關的代碼和整個項目。 Stephen Grider是一位出色的老師,他的表現非常好!

這是一種不會將重定向放入狀態樹的方式。