我正在尝试使用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>
);
}
我已经正确地导入了所有内容。不知道是什么原因导致错误。
1条答案
按热度按时间rsaldnfx1#
问题
store
未从editQuoteModalSlice
导入正确的导出。store.js
reducer函数是
editQuoteModalSlice
的***默认***导出,不是命名导出。editQuoteModalSlice.js
editQuoteModalSlice
在store.js
中未定义为import,并在创建store对象时作为reducer传递。store.js
解决方案
从
editQuoteModalSlice
文件导入正确的导出。store.js