javascript - react redux async action 完成函数后调用下一个函数

标签 javascript reactjs redux

假设我有一个调用 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(userInfo()) 函数在 dispatch(AuthApi())

中的所有处理之后被调用

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

dispatch(AuthApi()) 完全完成后,我如何才能只调用我的其他函数或逻辑或曾经的 console.log()

谢谢

最佳答案

您可以使用 Promises,它们与 thunkMiddleware 完美配合:

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

More examples here

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

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();
        })    
    }
}

关于javascript - react redux async action 完成函数后调用下一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35284248/

相关文章:

javascript - 基于单选选择的模态图像作为数组索引

javascript - Angular : Mixing provider and custom service in module's config/run

javascript - React 和 jest 模拟模块

reactjs - 类型 'amp-img' 上不存在属性 'JSX.IntrinsicElements'

reactjs - 无法从 React Native 应用程序中的 fetch 访问 json 服务器

react-native - 使用 Redux 工具包中的 createEntityAdapter 时如何将实体作为类组件中的数组获取?

reactjs - React + Redux 中 dom 操作的复杂性

javascript - 如何点击元素(对于整个文档)?

javascript - 为什么 this.setState 没有更新 this.states?

javascript - 由于滚动菜单消失,使用 flexbox 的固定元素在 iPhone 移动 Safari 上重新定位