首次进入Dashboard页面触发TypeError错误的修复及Section组件渲染方案
问题修复与即时渲染实现方案
问题概述
首次跳转至/dashboard页面时抛出Uncaught TypeError: Cannot read properties of undefined (reading 'includes'),刷新页面后正常渲染;同时需要实现进入页面后即时显示<Section />组件。
一、修复TypeError错误
1. 修正父组件useDispatch调用错误
父组件中useDispatch的写法有误,正确调用无需传入参数:
function Dashboard() { // 错误写法:const dispatch = useDispatch(getSections()) const dispatch = useDispatch() // 正确写法 useEffect(() => { dispatch(getSections()); }, [dispatch]) const location = useLocation() return ( <> <h1>Hello {location.state.teachersDetail.userName}</h1> <h1>This is where the chart and cards are located</h1> <Sections details={location.state.teachersDetail} /> </> ) }
2. 给数据添加空值保护
在Sections组件中,通过可选链操作符?.避免访问undefined属性,同时优化数组处理逻辑:
function Sections({ details }) { // 确保sections初始为空数组,避免undefined const sections = useSelector((state) => state.sections || []) // 给teacherId添加空值保护 const teacherId = details?.id; const [availableSection, setAvailableSection] = useState([]) useEffect(() => { // 过滤出包含当前teacherId的section,同时检查teachers属性是否存在 const availSection = sections.filter(section => section?.teachers?.includes(teacherId) ) setAvailableSection(availSection); }, [sections, teacherId]) // 添加teacherId到依赖项,确保details变化时重新计算 // 渲染部分... }
3. 设置Redux初始状态
在对应的Redux reducer中,给sections设置初始值为空数组:
const initialState = { sections: [] // 初始状态设为空数组 } function sectionReducer(state = initialState, action) { switch(action.type) { case 'GET_SECTIONS_SUCCESS': return { ...state, sections: action.payload } default: return state } }
二、实现<Section />即时渲染
移除冗余状态,直接计算可用sections
不需要通过useState和useEffect维护availableSection,直接在渲染阶段计算,避免状态更新的延迟:
function Sections({ details }) { const sections = useSelector((state) => state.sections || []) const teacherId = details?.id; // 直接计算符合条件的sections,无需额外状态 const availableSection = sections.filter(section => section?.teachers?.includes(teacherId) ) return ( !sections.length ? <CircularProgress /> : ( <Grid container direction="column" justifyContent="flex-start" alignItems="stretch" style={{margin:'0 auto'}} > {availableSection.map((section) => ( <Grid key={section._id} item xs={12} sm={6}> <Section section={section}/> </Grid> ))} </Grid> ) ) }
这样当sections或teacherId更新时,availableSection会立即同步计算,实现组件的即时渲染。
内容的提问来源于stack exchange,提问作者Charlz Ivan John Babida
相关产品推荐
相关产品推荐

