无法读取未定义的属性“用户”,React Redux
2021-04-12
717
我在 userSlice.js 中收到此错误 “无法读取未定义的属性‘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;
1个回答
问题就在这里
export const selectUser = state => state.user.user;
你在这里创建了名为
counter
的切片
export default configureStore({
reducer: {
counter: userReducer,
},
});
尝试
export const selectUser = state => state.counter.user;
或者将
counter
重命名为
user
Ivan Stelmakh
2021-04-12