我收到了这个错误"无法读取未定义的"的属性"user">在userSlice.js中,默认情况下在react redux中命名为counterSlice.js。我也尝试过通过更改名称和函数名来导出,我想我导出的是正确的函数。
有什么建议或解决方案可以让它运行吗?
这是我的userSlice.js文件,
import { createSlice } from '@reduxjs/toolkit';
export const userSlice = createSlice({
name: 'user',
initialState: {
user: null,
},
reducers: {
login: (state, action) => {
state.user = action.payload;
},
logout: (state) => {
state.user = null;
},
},
});
export const { login, logout} = userSlice.actions;
export const selectUser = state => state.user.user;
export default userSlice.reducer;
这是store.js文件,
import { configureStore } from '@reduxjs/toolkit';
import userReducer from '../features/userSlice';
export default configureStore({
reducer: {
counter: userReducer,
},
});
这是App.js文件,我正试图在其中创建要登录的登录用户状态
import React, {useEffect} from 'react';
import './App.css';
import Homescreen from "./screens/Homescreen";
import LoginScreen from "./screens/LoginScreen";
import {auth} from "./firebase";
import {useDispatch, useSelector} from "react-redux";
import {login, logout, selectUser} from "./features/userSlice";
import {BrowserRouter as Router, Switch,Route} from 'react-router-dom';
function App() {
const user = useSelector(selectUser);
const dispatch = useDispatch();
useEffect(() => {
const unsubscribe = auth.onAuthStateChanged((userAuth) => {
if(userAuth){
dispatch(login({
uid: userAuth.uid,
email: userAuth.email,
})
);
} else{
dispatch(logout())
}
});
return unsubscribe;
}, []);
return (
<div className="App">
<Router>
{!user ? (
<LoginScreen/>
):(
<Switch>
<Route exact path="/">
<Homescreen />
</Route>
</Switch>
)}
</Router>
</div>
);
}
export default App;
问题在这里
export const selectUser = state => state.user.user;
您在此处创建了名为counter
的切片
export default configureStore({
reducer: {
counter: userReducer,
},
});
尝试
export const selectUser = state => state.counter.user;
或将counter
重命名为user