在我的React Redux项目中,我正在编写一个thunk,并且希望它只有在之前的更新(如果有的话(已经完成的情况下才能调度。我知道thunks是帮助我们延迟向reducer调度操作的方法,它们也可以是异步的。以下是我的暴徒现在的样子:
myThunkMethod = () => async (dispatch, getState) =>{
dispatch(...my action...);
}
但是我如何才能使调度只有在上一次调用/状态更新完成之后才能调用
以下是您需要做的:
const firstThunk = () => (dispatch, getState) => {
// do or dispatch something here
return Promise.resoleved("first thunk resolved");
}
const secondThunk = () => (dispatch, getState) => {
// do or dispatch something here
return Promise.resolved("second thunk resolved")
}
const thirdThunk = () => (dispatch, getState) => {
// I want to first dispatch the first thunk
dispatch(firstThunk()).then(result => {
// first thunk successfully dispatched now it's time for secondThunk
dispatch(secondThunk()).then(res => {
// here both firstThunk and secondThunk dispatched successfully
})
})
}
只要thunk返回promise:(dispatch,getState)=>Promise
,就可以组合并等待thunk完成。
const thunkA = (arg) => (dispatch, getState) => {
//do stuff and RETURN PROMISE
return Promise;
};
const thunkB = (arg) => (dispatch, getState) => {
//do stuff and RETURN PROMISE
return Promise;
};
//combined thunk
const combinedThunk = (arg) => (dispatch, getState) =>
tunkA(arg)(dispatch, getState).then(() =>
thunkB(arg)(dispatch, getState)
);
//from component
const Component = () => {
const dispatch = React.useDispatch();
React.useEffect(() => {
dispatch(thunkA("some arg")).then(() =>
dispatch(thunkB("someArg"))
);
}, [dispatch]);
};
以下是如何进行递归thunk:
const recursiveThunk = (times) => (dispatch, getState) => {
if (times === 0) {
return;
}
dispatch(started());
somePromise().then(
(result) => {
dispatch(success());
return recursiveThunk(times - 1)(dispatch, getState);
},
(reject) => dispatch(failed())
);
};
目前还不清楚你在问题和评论中想要什么,但如果你想每次都用数组中的一个项目作为参数调用thunkA,那么你可以这样做:
const combinedThunk = (args) => (dispatch, getState) => {
if (args.length === 0) {
return;
}
return tunkA(args[0])(dispatch, getState).then(
() => combinedThunk(args.slice(1))(dispatch, getState),
(reject) => dispatch(failed(reject))
);
};
//call thunkA with 1, then 2 and then 3
dispatch(combinedThunk([1, 2, 3]));