反应 Redux 异步操作在完成函数后调用下一个函数

react redux async action call next function after finishing the function

本文关键字:函数 调用 下一个 Redux 异步操作 反应      更新时间:2023-09-26

假设我有一个调用 api 的函数:

export default function AuthApi({url, method, headers, data}={}){
    return (dispatch, getState) => {
        fetch(url, {
            method: method || null,
            headers: headers || null,
            body: form || null,
            }).then(function(response) {
                return response.json();
            }).then(function(response){
                console.log(response)
            })
    }
}

现在我想在某个地方调用这个 api:

      dispatch(AuthApi({url: "some_url", method: "POST", data: data}))
      console.log("called api")
      dispatch(userInfo(response))
      console.log(getState())
      router.pushState(null, '/profile')

在这里,我用 dispatch 调用 api,然后dispatch(userInfo).我假设在 dispatch(AuthApi()) 中的所有处理之后调用我的 dispatch(userInfo()) 函数

但是在这里它进入AuthApi()但没有完成它就开始调用其他函数或进程

我怎么能只调用我的其他函数或逻辑,或者在dispatch(AuthApi())完全完成后console.log()

谢谢

您可以使用 Promises,它们与 thunkMiddleware 配合得很好:

dispatch(AuthApi({url: "some_url", method: "POST", data: data})).then((response) => {
    dispatch(userInfo(response))
})

更多例子在这里

更新您还应该修改操作以返回承诺。

export default function AuthApi({url, method, headers, data}={}){
    return (dispatch, getState) => {    
        return fetch(url, {
            method: method || null,
            headers: headers || null,
            body: form || null,
        }).then(function(response) {
            return response.json();
        })    
    }
}