Redux中访问isAuthenticated报undefined错误求助
Redux访问isAuthenticated提示undefined问题排查
问题描述
报错信息:
Cannot read properties of undefined (reading 'isAuthenticated') at Function.mapStateToProps
全局状态的state.authReducer下存在isAuthenticated变量,但访问时仍提示该变量为undefined。使用Redux开发,怀疑问题出在store.js但无法定位,尝试过其他类似问题的解决方案无效。
补充:将connect()第一个参数设为null时组件可渲染,传入mapStateToProps则无法渲染,且isAuthenticated始终为undefined。
相关代码
store.js
const initialState = {}; const middleware = [thunk]; const store = legacy_createStore( rootReducer, initialState, composeWithDevTools(applyMiddleware(...middleware)) ); export default store;
authReducer.js
const initialState = { token: localStorage.getItem('token'), isAuthenticated: null, loading: true, user: null, }; const authReducer = (state = initialState, action) => { const { type, payload } = action; switch (type) { case LOGIN_SUCCESS: localStorage.setItem('token', payload.token); return { ...state, ...payload, isAuthenticated: true, loading: false, }; case LOGIN_FAIL: localStorage.removeItem('token'); return { ...state, token: null, isAuthenticated: false, loading: false, }; default: return state; } };
Login.js
const Login = ({ loginUser, isAuthenticated }) => { const [formData, setFormData] = useState({ email: '', password: '', }); const { email, password } = formData; const onChange = (e) => { setFormData({ ...formData, [e.target.name]: e.target.value }); }; const onSubmit = async (e) => { e.preventDefault(); loginUser(email, password); }; // Redirect if logged in if (isAuthenticated) { return <Navigate to='/dashboard' />; } return(some JSX form) Login.propTypes = { login: PropTypes.func.isRequired, isAuthenticated: PropTypes.bool, }; const mapStateToProps = (state) => ({ isAuthenticated: state.auth.isAuthenticated, }); export default connect(null, { loginUser })(Login);
问题解决步骤
修正mapStateToProps的路径错误
你在mapStateToProps里写的是state.auth.isAuthenticated,但你的reducer名为authReducer。需要根据rootReducer的组合方式调整:- 如果rootReducer里是把
authReducer命名为auth(如下方代码),则路径正确; - 如果rootReducer里直接用
authReducer作为键名,那要改成state.authReducer.isAuthenticated。
// 示例rootReducer正确写法 import { combineReducers } from 'redux'; import authReducer from './authReducer'; const rootReducer = combineReducers({ auth: authReducer // 这里的键名决定了state中的路径 });- 如果rootReducer里是把
修正connect的参数传递
你当前connect(null, { loginUser })(Login)传入的第一个参数是null,导致mapStateToProps根本没生效。需要改成:export default connect(mapStateToProps, { loginUser })(Login);修正propTypes的字段名错误
Login.propTypes里写的是login: PropTypes.func.isRequired,但组件实际接收的是loginUser,要改成:Login.propTypes = { loginUser: PropTypes.func.isRequired, isAuthenticated: PropTypes.bool, };
内容的提问来源于stack exchange,提问作者DanisJa
相关产品推荐
相关产品推荐

