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

React中Cannot read properties of undefined错误求助

问题修复:Cannot read properties of undefined reading 'Id'

错误场景

错误出现在PostWidget组件的const isLiked = Boolean(likes[loggedInUserId]);行,触发原因是尝试访问未定义对象的属性,导致首页渲染失败。

核心原因及修复方案

1. likes参数未初始化或为空

父组件未传递likes属性、接口返回的帖子数据中likes字段缺失/未加载完成,都会导致likes为undefined,无法通过[]访问用户ID对应的点赞状态。

修复方式二选一:

  • 解构props时给likes设置默认空对象:
const PostWidget = ({
  postId,
  postUserId,
  name,
  description,
  location,
  picturePath,
  userPicturePath,
  likes = {}, // 默认空对象
  comments,
}) => {
  // 后续逻辑不变
}
  • 使用可选链操作符做安全访问:
const isLiked = Boolean(likes?.[loggedInUserId]);

2. loggedInUserId未获取到值

如果Redux中state.user还未初始化(比如用户未登录、用户信息异步请求未返回),state.user._id会返回undefined,也可能间接引发错误。

修复:
给loggedInUserId设置默认值,或提前判断用户状态:

// 给用户ID设置默认空字符串
const loggedInUserId = useSelector((state) => state.user?._id || '');

// 或者未登录时不渲染组件/显示加载状态
if (!loggedInUserId) {
  return <div>加载中...</div>;
}

3. 检查变量拼写

注意你描述中错误行写的是loggedInUsrId,但代码里实际是loggedInUserId,如果实际代码存在拼写不一致,会导致访问likes[未定义变量],请自行核对代码拼写。

额外优化

为避免同类空值错误,建议给所有外部传入的props设置默认值:

const PostWidget = ({
  postId = '',
  postUserId = '',
  name = '',
  description = '',
  location = '',
  picturePath = '',
  userPicturePath = '',
  likes = {},
  comments = [],
}) => {
  // 组件逻辑
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:15:25