Redux登录后Sidebar报错:Cannot read properties of null (reading 'category_affiliation')
问题描述
使用Redux状态管理实现登录功能后,Sidebar.jsx组件出现报错:TypeError: Cannot read properties of null (reading 'category_affiliation'),登录后无法立即正确渲染admin数据。
相关代码
Sidebar.jsx
const Sidebar = () =>{ const { admin } = useSelector((state) => state.admin); let techSuperAdmin = admin && admin.techAdmin ? admin.techAdmin : false; let techAdminCategory = admin && admin.category_affiliation ? admin.category_affiliation : null; }
登录处理代码
const handleLogin = async (e) =>{ e.preventDefault() try { await LoginUser(userAdmin, dispatch) } catch (error) { console.log(error) } }
MyAdminSlice.jsx
export const adminSlice = createSlice({ name: 'admin', initialState: { admin: null, isFetching : false, isError: false, isSuccess: false, isUpdated: false, isMessage: "", }, reducers: { resetState: (state) =>{ state.admin = null; state.isFetching = false state.isError = false state.isSuccess = false state.isUpdated = false state.isMessage = "" }, loginStart: (state)=>{ state.isFetching = true; state.isError = false; }, loginSuccess: (state, action) =>{ state.isFetching = true; state.isSuccess = true; state.admin = action.payload, state.isMessage = ""; }, loginFailure: (state, action) =>{ state.isSuccess = false; state.isFetching = false; state.isError = true; state.isMessage = action.payload; }, logOut: (state) =>{ state.admin = null; }, } }) export const {resetState, loginStart, loginSuccess, loginFailure, logOut } = adminSlice.actions; export default adminSlice.reducer
解决方案
1. 修正Redux切片的登录成功状态
登录成功后请求已完成,需将isFetching设为false,避免状态逻辑混乱:
loginSuccess: (state, action) =>{ state.isFetching = false; // 此处改为false state.isSuccess = true; state.admin = action.payload; state.isMessage = ""; },
2. 优化Sidebar组件的安全取值逻辑
使用**可选链操作符(?.)**替代短路判断,同时结合isFetching状态处理加载中的情况,彻底避免admin为null时的属性读取报错:
const Sidebar = () =>{ const { admin, isFetching } = useSelector((state) => state.admin); // 加载中显示占位内容 if (isFetching) { return <div>加载中...</div>; } // 可选链+空值合并运算符安全取值 const techSuperAdmin = admin?.techAdmin ?? false; const techAdminCategory = admin?.category_affiliation ?? null; // 后续渲染逻辑... }
补充说明
- 可选链操作符
?.会自动判断左侧值是否为null/undefined,若为空则直接返回undefined,不会继续读取后续属性,从根源避免报错。 - 空值合并运算符
??用于在左侧值为null/undefined时返回右侧默认值,比||更精准(不会把0、空字符串等合法假值当成空)。
内容的提问来源于stack exchange,提问作者Stykgwar
相关产品推荐
相关产品推荐

