reactjs 无法读取undefined的属性(正在读取'editQuoteModalShown')react-redux

aiazj4mn  于 2023-06-22  发布在  React
关注(0)|答案(1)|浏览(91)

我正在尝试使用react-redux和redux toolkit创建打开和关闭模态表单的功能。它抛出以下错误:

Uncaught TypeError: Cannot read properties of undefined (reading 'editQuoteModalShown')
  • store.jsx*
import { apiSlice } from "./api/apiSlice";
import { editQuoteModalSlice } from "../features/quotes/editQuoteModalSlice";

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    editQuoteModalSlice: editQuoteModalSlice,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true,
});

setupListeners(store.dispatch);
  • editQuoteModalSlice.jsx*
import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  editQuoteModalShown: false,
};

export const editQuoteModalSlice = createSlice({
  name: "editQuoteModalSlice",
  initialState,
  reducers: {
    setEditQuoteModalShownDispatch: (state, action) => {
      state.editQuoteModalShown = action.payload;
    },
  },
});

export const editQuoteModalShownSelector = (state) =>
  state.editQuoteModalSlice.editQuoteModalShown;

export const { setEditQuoteModalShownDispatch } =
  editQuoteModalSlice.actions;

export default editQuoteModalSlice.reducer;

我是这样使用选择器的:EditQuoteModal.jsx

import {
  editQuoteModalShownSelector,
  setEditQuoteModalShownDispatch,
} from "./editQuoteModalSlice";

export default function EditQuoteModal() {

  const editQuoteModalShown = useSelector(editQuoteModalShownSelector);

  return (
    <div>
      {editQuoteModalShown && (<Modal />)}
    </div>
  );
}

我已经正确地导入了所有内容。不知道是什么原因导致错误。

rsaldnfx

rsaldnfx1#

问题

store未从editQuoteModalSlice导入正确的导出。
store.js

import { editQuoteModalSlice } from "../features/quotes/editQuoteModalSlice";

reducer函数是editQuoteModalSlice的***默认***导出,不是命名导出。
editQuoteModalSlice.js

export default editQuoteModalSlice.reducer;

editQuoteModalSlicestore.js中未定义为import,并在创建store对象时作为reducer传递。
store.js

import {
  editQuoteModalSlice // <-- undefined
} from "../features/quotes/editQuoteModalSlice";

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    editQuoteModalSlice: editQuoteModalSlice, // <-- undefined reducer
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true,
});

解决方案

editQuoteModalSlice文件导入正确的导出。
store.js

import editQuoteModalReducer from "../features/quotes/editQuoteModalSlice";

export const store = configureStore({
  reducer: {
    [apiSlice.reducerPath]: apiSlice.reducer,
    editQuoteModalSlice: editQuoteModalReducer, // <-- defined reducer
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware().concat(apiSlice.middleware),
  devTools: true,
});

相关问题