繁体   English   中英

Redux 工具包异步 Thunk:无法读取未定义的属性

[英]Redux toolkit Async Thunk: Cannot read properties of undefined

我正在构建一个 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;
    }
  ),
};

我发现了这个问题。 我在我的 thunk 中向gridSlice发送了一个动作,但是切片也在导入 thunk,所以它产生了一个循环依赖。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM