当代码几乎相似时,Redux 选择器尝试在一个切片中导出状态而不是在另一个切片中导出状态时出错
2022-05-11
833
我是 redux 的新手,我创建了一个名为 eventmodalSlice 的切片,用于跟踪应用中的模式是打开还是关闭。当我创建选择器以导出状态时,出现错误。错误显示
TypeError:undefined 不是对象(评估“state.eventmodal”)
import React from "react"
import { createSlice } from "@reduxjs/toolkit"
export const eventmodalSlice = createSlice({
name: "eventmodal",
initialState:{
modalvisible: null
},
reducers: {
Close: (state, action) => {
state.modalvisible = action.payload;
},
Open: (state, action) => {
state.modalvisible = action.payload;
},
}
});
export const {Close, Open} = eventmodalSlice.actions;
export const selectEventModal = (state) => state.eventmodal.modalvisible;
export default eventmodalSlice.reducer;
我不确定是什么导致了此特定切片中的此错误,因为我有另一个名为 user 切片的切片,它看起来与此切片几乎相同。
import React from "react"
import { createSlice } from "@reduxjs/toolkit"
import { act } from "react-test-renderer";
export const userSlice = createSlice({
name: "user",
initialState:{
user: null
},
reducers: {
Signin: (state, action) => {
state.user = action.payload;
},
Register: (state, action) => {
state.user = action.payload;
},
Signout: (state) => {
state.user = null;
}
}
});
export const { Signin, Register, Signout} = userSlice.actions;
export const selectUser = (state) => state.user.user;
export default userSlice.reducer;
State.user.user 在最后一个代码片段中没有错误。这是最令人困惑的,因为除非我遗漏了某些内容,否则这些代码片段看起来几乎相同。任何帮助都将不胜感激。
我的商店看起来像这样
import { configureStore } from "@reduxjs/toolkit";
import userReducer from "./userSlice"
import eventmodalReducer from "./eventmodalSlice"
export default configureStore({
reducer: {
user: userReducer,
eventmodal: eventmodalReducer
},
});
2个回答
import { configureStore } from "@reduxjs/toolkit";
import userSlice from "./userSlice"
import eventmodalReducer from "./eventmodalSlice"
const store = configureStore({
reducer: {
user: userSlice.reducer,
eventmodal: eventmodalReducer
},
});
export default store;
prince Tash
2022-09-20
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import store from './app/store';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<Provider store={ store}>
<App />
</Provider>
</React.StrictMode>
);
reportWebVitals();
prince Tash
2022-09-20