我正在学习如何使用AsyncThunk。我创建了一个简单的计数器应用程序。它有一个加法和减法按钮。单击这些按钮后,计数器值将相应地增加或减少。
现在我想再添加两个按钮,单击它们时应该执行相同的递增和递减操作,但应该延迟一秒。
当我不使用redux toolkit时,我也能做到这一点。这个StackBlitz has the code without toolkit
但我不知道如何使用redux toolkit来实现同样的功能。有人能指导我如何编写我的AsyncThunk调用和extraReducers来实现同样的目标吗?
这个Stackblitz contains an example of what I had tried with toolkit
我不知道如何继续我的createAsyncThunk
呼叫。我尝试在createAsync
回调函数中调度操作,但没有成功。
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
export const asyncAdd = createAsyncThunk('asyncAdd', async (_, thunkAPI) => {
});
const counterSlice = createSlice({
name: 'counter',
initialState: {
count: 0,
hasError: false,
isLoading: false,
users: {},
todos: {},
},
reducers: {
add: (state, action) => {
state.count += action.payload;
},
sub: (state) => {
state.count -= 1;
},
},
extraReducers: {
[asyncAdd.pending]: (state, action) => {
state.hasError = false;
state.isLoading = true;
console.log('PENDING');
},
[asyncAdd.fulfilled]: (state, action) => {
state.hasError = false;
state.isLoading = false;
console.log('payload ' + action.payload);
state.count = action.payload;
console.log('FULILLED');
},
[asyncAdd.rejected]: (state, action) => {
state.hasError = true;
state.isLoading = false;
console.log('REJECTED');
},
},
});
export const { add, sub } = counterSlice.actions;
export default counterSlice.reducer;
1条答案
按热度按时间v8wbuo2f1#
createAsyncThunk
被设计为使用promises
来处理一些延迟的操作,你必须返回一个promise
或一个已解析的promise值。使用
extraReducers
中的builder
对象创建待定、拒绝和已完成的案例我也叉了stackblitz