我必须在Redux工具箱中连续链接两个动作,但到目前为止,我只能并行地做到这一点。下面是我试图折射的片段。如何在第一个动作比赛后强制第二个动作开始?
const onSubmit = async () => {
await Promise.all([
dispatch(action1({})),<-- wait before second action starts.
dispatch(action2({}))
]);
};
由于createAsyncThunk
返回一个标准Redux的动作创建者。RTK将redux-thunk
添加为默认中间件。可以使用redux-thunk
的合成特性。这样你就可以基于JS的承诺链调用特性来串行地调度动作创建者
内部函数的任何返回值都可以作为分派本身的返回值。这对于编排异步控制流是很方便的,异步控制流包含了多个动作创建者相互调度并返回承诺以等待彼此的完成
。
import { createAsyncThunk, createSlice, configureStore } from '@reduxjs/toolkit';
const api = () => new Promise((resolve) => setTimeout(resolve, 1000));
const action1 = createAsyncThunk('app/action1', async () => {
await api();
return 'action1 response';
});
const action2 = createAsyncThunk('app/action2', async () => {
return 'action2 response';
});
const usersSlice = createSlice({
name: 'app',
initialState: {},
reducers: {},
extraReducers: (builder) => {
builder.addCase(action1.fulfilled, (state, action) => {
return state;
});
},
});
export const store = configureStore({
reducer: {
users: usersSlice.reducer,
},
});
store
.dispatch(action1())
.then((res1) => {
console.log(res1);
return store.dispatch(action2());
})
.then((res2) => console.log(res2));
输出:
{
type: 'app/action1/fulfilled',
payload: 'action1 response',
meta: {
arg: undefined,
requestId: 'vQo835AGEI755Po5xWcER',
requestStatus: 'fulfilled'
}
}
{
type: 'app/action2/fulfilled',
payload: 'action2 response',
meta: {
arg: undefined,
requestId: 'KJmLsXzZCLxx2BslvkfNu',
requestStatus: 'fulfilled'
}
}