【问题标题】:Fetching from Redux-Toolkit store returns undefined从 Redux-Toolkit 存储中获取返回 undefined
【发布时间】:2021-12-28 06:11:04
【问题描述】:

我正在将我的代码从“旧”Redux 重构为 Redux-toolkit,但现在我的代码不会从存储中检索数据, 我仔细检查了我是否犯了很多次错误。 这是代码:

reduxStore

import {
  Action,
  configureStore,
  EnhancedStore,
  ThunkAction,
} from "@reduxjs/toolkit";

import tablesReducer from "./slices/tablesSlice";
// import bookingsReducer from "./slices/bookingsReducer";

import { DefaultStateI, TableI } from "../Interfaces";

export const configureStoreWithMiddlewares = (): EnhancedStore => {
  const store = configureStore({
    reducer: {
      tables: tablesReducer,
      // bookings: bookingsReducer,
    },
    middleware: (getDefaultMiddleware) =>
      getDefaultMiddleware({ serializableCheck: false }),

    devTools: process.env.NODE_ENV !== "production",
  });
  return store;
};

export const store = configureStoreWithMiddlewares();

// // Infer the `RootState` and `AppDispatch` types from the store itself
export type RootState = ReturnType<typeof store.getState>;
// // Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}
export type AppDispatch = typeof store.dispatch;
// // export default store;

export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

这是切片:

tablesSlice

import {
    createAction,
    createAsyncThunk,
    createReducer,
    createSlice,
    PayloadAction,
  } from "@reduxjs/toolkit";
  import axios, { AxiosError } from "axios";
  import { stat } from "fs";
  import { TableI } from "../../Interfaces";
  import { RootState } from "../reduxStore";
  
  export enum RetrieveState {
    Loading,
    Loaded,
    Error,
  }
  
  type RetrieveTables = {
    tables: TableI[];
  };

  
  
  export const fetchAllTables = createAsyncThunk(
    "tables/fetchAllTables",
  async (_, thunkAPI) => {
    try {
      const response = await axios.get<RetrieveTables>(
        "http://localhost:5000/tables"
        );
        return response.data.tables;
      } catch (error) {
        const axiosError = error as AxiosError;
      return thunkAPI.rejectWithValue({ errorMessage: axiosError.message });
    }
  }
);

const tablesSlice: any = createSlice({
  name: "tables",
  initialState: {
    tables: new Array<TableI>(),
    tablesFiltered: [],
    capacity: 0,
    location: "",
    bookings: [],
    error: RetrieveState.Error,
    loading: false,
  },
  reducers: {},
  extraReducers: (builder) => {
    builder.addCase(fetchAllTables.pending, (state) => {
      state.loading = true;
    });
    builder.addCase(fetchAllTables.fulfilled, (state: any, action) => {
      state.loading = false;
      state.tables = action.payload as TableI[];
    });
    builder.addCase(fetchAllTables.rejected, (state, action) => {
      state.loading = false;
      state.error = action.payload as RetrieveState.Error;
    });
  },
});

export const tablesSelector = (state: RootState) => {
  return state.tables.tables;
};

export default tablesSlice.reducer;

然后我只需在中获取数据

App.tsx

// React
import React, { useEffect } from "react";
import { Switch, Route } from "react-router-dom";

// Redux
import { useDispatch, useSelector } from "react-redux";
import { fetchAllTables } from "./store/slices/tablesSlice";

const App: React.FC = () => {
  const dispatch = useDispatch();**

  useEffect(() => {
    dispatch(fetchAllTables());
  }, [dispatch]);

  const tables: Array<TableI> = useSelector(tablesSelector);
  console.log(tables)

如果我console.log(tables) 结果是'undefined', 我真的很难理解为什么它不起作用 我还仔细检查了端点,该 url 工作正常

【问题讨论】:

    标签: reactjs redux react-redux axios redux-toolkit


    【解决方案1】:

    没关系,我找到了解决方案,这是一个非常简单的错误。 tablesSlice 正在尝试这个:

    返回 response.data.tables;

    我只需要这样做:

    return response.data;
    

    现在终于成功了!

    【讨论】:

      猜你喜欢
      • 2022-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-23
      • 2013-01-22
      • 2022-12-10
      • 1970-01-01
      相关资源
      最近更新 更多