createAsyncThunk 没有改变状态



所以,我正在尝试创建异步思考行动,模拟数据从文件到状态。

import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import mocktasks from './mocktasks';
export interface TasksState {
data: Task[];
}
const initialState: TasksState = {
data: [],
};
export const fetchTasks = createAsyncThunk('tasks/fetchTasks', () => mocktasks);
export const tasksSlice = createSlice({
name: 'tasks',
initialState,
reducers: {
setTasks: (state:TasksState, action: PayloadAction<Task[]>) => ({
...state,
data: action.payload,
}),
addTask: (state: TasksState, action: PayloadAction<Task>) => ({
...state,
data: [...state.data, action.payload],
}),
},
extraReducers: {
[fetchTasks.fulfilled.name]: (state, action: PayloadAction<Task[]>) => ({
...state,
data: action.payload,
}),
},
});
export const { setTasks, addTask } = tasksSlice.actions;
export default tasksSlice.reducer;

但是有一件奇怪的事情:即使已经分派了取回动作,我的状态也没有改变。状态和调度动作

我认为,有一个问题与传递有效载荷fetchTasks/completed,但Redux devtools显示,完成的有效载荷有正确的数据,这是从模拟文件获得:动作有效载荷

UPD:尽管如此,在createAsyncThunk中使用dispatch(setTasks(mocktasks))就像我需要的那样工作。

使用builder符号来避免打字错误(redux-toolkit文档的官方建议):

extraReducers: (builder) => {
.addCase(fetchTasks.fulfilled, (state) => ({
...state,
data: action.payload,
}))
},

[fetchTasks.fulfilled.type]应该工作,因为.name似乎总是返回字符串actionCreator

相关内容

  • 没有找到相关文章

最新更新