从 Redux-Toolkit 存储中获取返回 undefined

Posted

技术标签:

【中文标题】从 Redux-Toolkit 存储中获取返回 undefined【英文标题】:Fetching from Redux-Toolkit store returns 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 工作正常

【问题讨论】:

【参考方案1】:

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

返回 response.data.tables;

我只需要这样做:

return response.data;

现在终于成功了!

【讨论】:

以上是关于从 Redux-Toolkit 存储中获取返回 undefined的主要内容,如果未能解决你的问题,请参考以下文章

无法使用带有 redux-toolkit 的 socketIO 获取对象内函数的值

如何在 Redux-toolkit 中使用两个不同的切片?

如何在 Storybook 中使用 redux-toolkit?

从 react-redux 迁移到 redux-toolkit 后使用 configureStore 传递初始状态的最佳方法

如何实现redux-toolkit和next,js又不丢s-s-r

redux-toolkit 在来自另一个 thunk reducer 的同一切片中使用 actionCreater