我刚刚开始探索 react-redux 钩子(Hook),我很好奇如果我使用 thunk 和 useDispatch()
如何返回一个 promise。基本上我想实现以下目标:
const dispatch = useDispatch();
dispatch(myAction(...args)).then((result) => {
...do something with result
});
当我的 Action 看起来像这样时:
const myAction = (arg1, arg2) => {
return (dispatch, getState) => {
Promise.resolve(arg1 + arg2);
}
}
我已经大大简化了我的问题,但这基本上就是我要处理的问题。当我尝试分派(dispatch)上述操作时,出现错误 dispatch(...).then
is not a function.
我知道 redux hooks 很新,但我很好奇是否有人已经让它工作或者知道解决方案。我觉得完成这项工作应该相对容易,但我很茫然。如果您需要更多信息,请告诉我。在此先感谢您的帮助!
最佳答案
作为 dispatch
返回两个之一:
对于同步操作(如
dispatch ({type: 'ACTION'})
它将返回操作对象({type: 'ACTION'}
在我的示例)对于 thunk Action (返回函数的 Action 创建者),它返回从 Action 创建者返回的相同结果。
因此,对于您的情况,只需为您的 Action 创建者添加 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}));
}
}
在这种情况下,也将返回已解决的 promise 。 promise 的内容将是对象 {type: 'RESPONSE_RECEIVED', payload: response}
。
或者你可以像这样为返回的 promise 设置任意内容
const myAction = (arg1, arg2) => {
return (dispatch, getState) => {
return fetch(/* some request */).then(response => {
dispatch ({type: 'RESPONSE_RECEIVED', payload: response})
return response;
}
}
}
在此示例中,将返回已解决的 promise ,但其中包含 response
。
在任何情况下你都可以按照你想要的方式链接
dispatch(myAction(...args)).then((result) => {
...do something with result
});
关于javascript - 如何使用 thunk 和 useDispatch(react-redux Hook )从操作中返回 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56694102/