成功或错误后如何使用redux thunk重定向?

ish*_*ala 6 reactjs redux redux-thunk react-redux

我是Promises和React的新手.我在我的动作创建者中使用redux-thunk来解决promises,我正在调用我的组件中的动作创建器.在成功或不成功的请求完成后,如何路由到不同的URL?我正在附加删除功能动作创建者的代码.

成功时,我应该在发送时使用参数(routeTo)设置状态吗?

这是删除功能:

export function deletePost(id){
    var request = axios.delete(`${ROOT_URL}posts/${id}${API_KEY}`);

    return function(dispatch){
        request.then((response)=>{
            console.log("I deleted"+response.data.title);
        }).catch((error)=>{
            console.log("DELETE_ERROR: "+JSON.stringify(error));
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

我从我的组件中的onclick函数调用此函数.

deletePost(){
    this.props.deletePost(this.props.params.id);
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ung 13

我发现使用redux进行路由的最好方法是考虑我的状态的URI部分,并将其存储在redux中.有一个很棒的库react-router-redux可以为你做这件事.

一旦你有react-router-redux设置,那么你可以调度动作来改变位置,所以你的thunk看起来像:

import { push } from 'react-router-redux';

export function deletePost(id){
    var request = axios.delete(`${ROOT_URL}posts/${id}${API_KEY}`);

    return function(dispatch){
        request.then((response)=>{
            console.log("I deleted"+response.data.title);
            dispatch(push('/delete-success-uri'));
        }).catch((error)=>{
            console.log("DELETE_ERROR: "+JSON.stringify(error));
            dispatch(push('/delete-fail-uri'));
        });
    }
}
Run Code Online (Sandbox Code Playgroud)