2016-04-27 40 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是一位出色的老师,他的表现非常好!

这是一种不会将重定向放入状态树的方式。