You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用useSelector获取Redux数据时如何等待加载避免读取null属性报错

报错原因

初始状态下Redux中userData为null,组件首次渲染时useEffect里的异步接口请求还未完成,此时直接访问null的myPostList属性就会抛出该错误。

解决方案

提供三种常用实现方式,可按需选择:

  • 方案1:使用可选链运算符做安全访问,代码改动最小
    直接修改map调用的代码,用可选链?.避免访问空值属性,同时给空场景兜底空数组:
    const MyPost = userData?.myPostList?.map(
      (item:any, index:number) => {
        return(
          <tbody id = {"body" + index} key = {item.id}>
            <tr>
              <td id = "title">{item.postName}</td>
            </tr>
            <tr>
              <td id = "content">{item.content}</td>
            </tr>
          </tbody>
        )
      }
    ) || []
    
  • 方案2:提前判断渲染加载态,用户体验更好
    在获取userData后先判断是否存在,不存在时直接返回加载提示,避免执行后续的属性访问逻辑:
    const userData = useSelector((state : RootState) => state.User.userData)
    
    // 新增判断
    if (!userData) {
      return <div>用户信息加载中...</div>
    }
    
    // 后续原有逻辑保持不变
    const MyPost = userData.myPostList.map(...)
    
  • 方案3:修改Redux初始值从根源避免空值
    找到User模块的reducer定义,将userData的初始值从null修改为默认结构:
    // reducer初始值示例
    const initialState = {
      userData: {
        myPostList: []
      }
      // 其他原有状态
    }
    
优化后的完整代码示例

这里采用方案1做最小改动,同时修复原代码的隐含问题:

import { useDispatch, useSelector } from "react-redux";
import { GetUserInfo } from "../modules/action-creator";
import { RootState } from "../modules/Store";
import "../styles/mypage.scss";

function Mypage() {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(GetUserInfo())
  }, [dispatch]) // 补充dispatch依赖,消除ESLint警告

  const userData = useSelector((state : RootState) => state.User.userData)
  
  const MyPost = userData?.myPostList?.map(
    (item:any, index:number) => {
      return(
        <tbody id = {"body" + index} key = {item.id}>
          <tr>
            {/* 替换重复id为class,同页面id不能重复 */}
            <td className="title">{item.postName}</td>
          </tr>
          <tr>
            <td className="content">{item.content}</td>
          </tr>
        </tbody>
      )
    }
  ) || []
    
  return (
        <div className="mypost">
          <div className="post_info">
            {/* 动态显示帖子数量 */}
            전체글 {userData?.myPostList?.length || 0}개
            <button>글쓰기</button>
          </div>
          <table className="post_detail">{MyPost.length === 0 ? "표시할 정보가 없습니다." : MyPost}</table>
        </div>
  )
}

内容的提问来源于stack exchange,提问作者sunpl13

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:51:02