如何 return 使用 thunk 和 useDispatch(react-redux 挂钩)从操作中获得承诺?

How to return a promise from an action using thunk and useDispatch (react-redux hooks)?

我刚开始探索 react-redux 钩子,我很好奇如果我使用 thunk 和 useDispatch() 如何 return 一个 promise。本质上我想实现以下目标:

const dispatch = useDispatch();

dispatch(myAction(...args)).then((result) => {
    ...do something with result
});

当我的动作看起来像这样时:

const myAction = (arg1, arg2) => {
    return (dispatch, getState) => {
        Promise.resolve(arg1 + arg2);
    }
}

我已经大大简化了我的问题,但这基本上就是我要处理的问题。当我尝试分派上述操作时,出现错误 dispatch(...).then is not a function.

我知道 redux hooks 很新,但我很好奇是否有人已经让它工作或者知道解决方案。我觉得完成这项工作应该相对容易,但我很茫然。如果您需要更多信息,请告诉我。在此先感谢您的帮助!

作为 dispatch returns 两者之一:

  1. 对于同步操作(如 dispatch ({type: 'ACTION'}) 它将 return 操作对象(在我的示例中为 {type: 'ACTION'}

  2. 对于 thunk 动作(return 起作用的动作创建者),return与动作创建者 return 产生的结果相同。

因此,对于您的情况,只需为您的动作创建者添加 return 声明

const myAction = (arg1, arg2) => {
    return (dispatch, getState) => {
        return Promise.resolve(arg1 + arg2);
    }
}

你可以像这样myAction更逼真

const myAction = (arg1, arg2) => {
    return (dispatch, getState) => {
        return fetch(/* some request */).then(response => dispatch ({type: 'RESPONSE_RECEIVED', payload: response}));
    }
}

在这种情况下,已解决的承诺也将被 returned。承诺的内容将是对象 {type: 'RESPONSE_RECEIVED', payload: response}

或者您可以像这样returned promise 设置任意内容

const myAction = (arg1, arg2) => {
    return (dispatch, getState) => {
        return fetch(/* some request */).then(response => { 
            dispatch ({type: 'RESPONSE_RECEIVED', payload: response})
            return response;
        }
    }
}

在此示例中,解析的承诺将被 returned 但其中包含 response 内部。

在任何情况下,您都可以按照自己的意愿进行链接

dispatch(myAction(...args)).then((result) => {
    ...do something with result
});