【问题标题】:Redux toolkit Async Thunk: Cannot read properties of undefinedRedux 工具包 Async Thunk:无法读取未定义的属性
【发布时间】:2021-11-30 23:52:54
【问题描述】:

我正在构建一个 redux 工具包网站,我将在其中创建一个网格。因此,为了使用这个网格,我使用异步 thunk 从后端获取数据,然后将其发送到我的 redux 切片。此代码正在运行,但是当我与其他更改合并时,它停止了。我已经把默认导出改成普通的export default test = { ... },然后错误改成“初始化前无法访问测试”。

我的切片:

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { AnyObject } from "../../models/utils/anyObject";
import { PageResponse } from "../../models/utils/pageResponse";
import thunk from "../thunks/grid";

interface GridState {
  data: PageResponse<AnyObject> | null;
  carregando: boolean;
  totalDeItems: number;
}

const initialState: GridState = {
  data: null,
  carregando: false,
  totalDeItems: 0,
};

const gridSlice = createSlice({
  name: "grid",
  initialState,
  reducers: {
    setCarregando: (state, action: PayloadAction<boolean>) => {
      state.carregando = action.payload;
    },
  },
  extraReducers: (builder) => {
    builder.addCase(thunk.getData.fulfilled, (state, { payload }) => {
      state.data = payload;
      state.totalDeItems = payload.totalItems;
    });
  },
});

export const gridActions = gridSlice.actions;
export default gridSlice;

我的电话:

import { AsyncThunkAction, createAsyncThunk } from "@reduxjs/toolkit";
import { AnyObject } from "../../models/utils/anyObject";
import { PageOptions } from "../../models/utils/pageOptions";
import { PageResponse } from "../../models/utils/pageResponse";
import { gridActions } from "../slices/grid";

interface GridDataProps {
  thunk: (
    arg: PageOptions
  ) => AsyncThunkAction<PageResponse<AnyObject>, PageOptions, AnyObject>;
  options?: PageOptions;
}

export default {
  getData: createAsyncThunk(
    "grid/data",
    async (props: GridDataProps, { dispatch }) => {
      dispatch(gridActions.setCarregando(true));
      const response = await dispatch(
        props.thunk(
          props.options || {
            currentPage: 1,
            itemsPerPage: 4,
          }
        )
      );
      dispatch(gridActions.setCarregando(false));
      const result = response.payload as PageResponse<AnyObject>;
      return result;
    }
  ),
};

【问题讨论】:

    标签: reactjs asynchronous async-await react-redux redux-toolkit


    【解决方案1】:

    我发现了问题。我正在向我的 thunk 中的 gridSlice 发送一个操作,但切片也在导入 thunk,因此它产生了循环依赖。

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2019-01-29
      • 2022-12-21
      • 2023-02-15
      • 2023-01-20
      • 2020-10-10
      • 2019-02-15
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多