createAsyncThunk 没有改变状态

createAsyncThunk isn't changing state

所以,我正在尝试创建异步 thunk 操作,以模拟从文件到状态的数据。

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;

但有一件奇怪的事情:尽管提取操作已经发送,但我的状态没有改变。 State and dispatched actions

我认为,将有效载荷传递给 fetchTasks/fulfilled 时存在问题,但 Redux devtools 显示,有效载荷中有正确的数据,该数据是从模拟文件中获得的:Action payload

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

使用 builder 符号来避免打字稿错误(official recomendation 来自 redux-toolkit 文档):

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

[fetchTasks.fulfilled.type] 应该有效,因为 .name 似乎总是 return 字符串 actionCreator.