Redux Thunk-级联调度调用
在我的React-Redux项目中,我正在编写一个thunk,并且只希望在上一次更新(如果有)完成时才发送它。我知道thunks是帮助我们延迟向reducer分配操作的方法,它们也可以是异步的。下面是我的thunk现在的样子:Redux Thunk-级联调度调用,redux,react-redux,redux-thunk,thunk,Redux,React Redux,Redux Thunk,Thunk,在我的React-Redux项目中,我正在编写一个thunk,并且只希望在上一次更新(如果有)完成时才发送它。我知道thunks是帮助我们延迟向reducer分配操作的方法,它们也可以是异步的。下面是我的thunk现在的样子: myThunkMethod = () => async (dispatch, getState) =>{ dispatch(...my action...); } 但是我如何才能在上一次调用/状态更新完成后调用dispatch您可以合并并等待thun
myThunkMethod = () => async (dispatch, getState) =>{
dispatch(...my action...);
}
但是我如何才能在上一次调用/状态更新完成后调用dispatch您可以合并并等待thunk完成,只要thunk返回一个承诺:
(dispatch,getState)=>promise
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]);
};
下面是如何进行递归重击:
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]));
以下是您需要做的:
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
})
})
}
谢谢你的努力,但是不要打A,B。。有限的,我的意思是:A->A->A->…->A where is A is A is the same thunk,但是调度只在前一个调用完成后发生complete@DivyanshGoenka所以你想要一个递归的thunk,我把它添加到了答案中。谢谢你的努力,但不是thunk a,B。。有限的,我的意思是:A->A->A->…->A where is A is A is the same thunk,但是只有在前一个调用完成后才会进行分派