javascript - Redux thunk : return promise from dispatched action

标签 javascript html reactjs redux redux-thunk

是否可以从 action creator 返回 promise/signal,当 Redux thunk 成功派发特定 action 时解决?

考虑这个 Action 创建者:

function doPost(data) {
    return (dispatch) => {
        dispatch({type: POST_LOADING});
        Source.doPost() // async http operation
            .then(response => {
                dispatch({type: POST_SUCCESS, payload: response})
            })
            .catch(errorMessage => {
                dispatch({type: POST_ERROR, payload: errorMessage})
            });
    }
}

当 Redux 已分派(dispatch) POST_SUCCESS 或 POST_ERROR 操作时,我想在调用 doPost 操作创建器之后异步调用组件中的某些函数。一种解决方案是将回调传递给 action creator 本身,但这会使代码变得困惑并且难以掌握和维护。我也可以在 while 循环中轮询 Redux 状态,但那样效率很低。

理想情况下,解决方案应该是一个 promise ,它应该在某些操作(在本例中为 POST_SUCCESS 或 POST_ERROR)被调度时解决/拒绝。

handlerFunction {
  doPost(data)
  closeWindow()
}

上面的例子应该重构,所以只有在 doPost() 成功时才调用 closeWindow()。

最佳答案

当然,您可以从异步操作返回 promise :

function doPost(data) {
    return (dispatch) => {
        dispatch({type: POST_LOADING});
        // Returning promise.
        return Source.doPost() // async http operation
            .then(response => {
                dispatch({type: POST_SUCCESS, payload: response})
                // Returning response, to be able to handle it after dispatching async action.
                return response;
            })
            .catch(errorMessage => {
                dispatch({type: POST_ERROR, payload: errorMessage})
                // Throwing an error, to be able handle errors later, in component.
                throw new Error(errorMessage)
            });
    }
}

现在,dispatch 函数返回一个 promise:

handlerFunction {
  dispatch(doPost(data))
      // Now, we have access to `response` object, which we returned from promise in `doPost` action.
      .then(response => {
          // This function will be called when async action was succeeded.
          closeWindow();
      })
      .catch(() => {
          // This function will be called when async action was failed.
      });
}

关于javascript - Redux thunk : return promise from dispatched action,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38329921/

相关文章:

javascript - jQuery 可拖动停止 : function to stopPropagation of elements

Javascript 鼠标悬停在动态数量的元素上

javascript - JavaScript 函数中的 JSON 数据渲染

javascript - 打印分页表(simplePagination.js by flaviusmatis)

javascript - Chart.js 中 x 轴上的双标签

javascript - react-native fetch async/await 响应过滤

javascript - 删除包装 div

javascript - Javascript音频功能不起作用

reactjs - 如何将 getFieldDecorator 与 React (function) hooks 一起使用

javascript - 如何使用从 Redux 返回的嵌套数据结构而不遇到 'cannot access property x of undefined' 等错误?