成功执行异步Redux操作后过渡到路由

时间:2020-07-16 13:54:30

标签: reactjs react-redux axios

当我通过API调用删除category时,Redux不会等待所有操作完成。下面的操作示例:

export const deleteCategory=(id)=>{
    return dispatch=>{
        const message='Category Deleted Successfully!'
        dispatch(deleteCategoryStart())
        axios.delete(`http://127.0.0.1:8000/admindashboard/categories/${id}/`)
        .then(res=>{
            dispatch(deleteCategorySuccess(message))
        }).catch(err=>{
            dispatch(deleteCategoryFailed(err))
        })
    }
}

我处理删除的代码:

handleDelete= (event) =>{
      event.preventDefault();
      this.props.deleteCategory(this.props.match.params.categoryID);
      this.props.history.push('/categories')
}

我正在尝试删除category,并将用户重定向到“所有类别”页面。相反,它会在完成所有操作分派之前重定向用户。新的类别页面/组件将调用其他操作,以获取所有类别。

动作顺序:

enter image description here

1 个答案:

答案 0 :(得分:0)

JavaScript明确地不会等待您的外部过程(API调用)完成。您可以使用::operator new或类似于以下内容更改代码

async/await
export const deleteCategory = (id) => {
    return dispatch => {
        dispatch(deleteCategoryStart());
        return axios.delete(`http://127.0.0.1:8000/admindashboard/categories/${id}/`);
    }
}