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

求助:退出个人资料页时出现Cannot read properties of undefined (reading 'name')错误

个人资料页退出登录报错的定位与修复

问题描述

在个人资料页执行退出登录操作时,页面短暂抛出错误:Cannot read properties of undefined (reading 'name'),网站其他功能正常,仅该页面退出时出现此问题。

错误截图

错误提示截图

问题根源

退出登录时,Redux中userLogin状态下的userInfo会被清空(变为undefined),但此时个人资料页尚未完成跳转或卸载,组件重新渲染时直接访问userInfo.name、userInfo.createdAt这类属性,就会触发undefined读取属性的错误。其他页面无此问题,是因为它们没有直接依赖userInfo的属性进行渲染。

修复方案

1. 可选链操作符(最简洁)

在ProfileScreen.js中,给userInfo的属性访问添加可选链?.,同时设置默认值避免空白:

// 修改作者卡片名称部分
<h5 className="author-card-name mb-2">
  <strong>{userInfo?.name || '访客'}</strong>
</h5>
// 修改加入时间部分
<span className="author-card-position">
  <>Joined {userInfo?.createdAt ? moment(userInfo.createdAt).format('LL') : '未知'}</>
</span>

2. 条件渲染(更直观)

判断userInfo存在时才渲染用户信息,否则显示默认内容:

<div className="author-card-details col-md-7">
  {userInfo ? (
    <>
      <h5 className="author-card-name mb-2">
        <strong>{userInfo.name}</strong>
      </h5>
      <span className="author-card-position">
        <>Joined {moment(userInfo.createdAt).format('LL')}</>
      </span>
    </>
  ) : (
    <>
      <h5 className="author-card-name mb-2">
        <strong>访客</strong>
      </h5>
      <span className="author-card-position">Joined 未知</span>
    </>
  )}
</div>

3. 优化退出逻辑(从根源避免)

修改退出登录的处理逻辑,清空用户信息后立即跳转到登录页或首页,不让个人资料页继续渲染:

// 示例退出action逻辑
const handleLogout = () => {
  localStorage.removeItem('userInfo');
  dispatch({ type: 'USER_LOGOUT' });
  // 立即跳转,终止当前页面渲染
  window.location.href = '/login';
};

额外优化建议

  • ProfileTabs.js的submitHandler中,访问user._id时也建议添加可选链:id: user?._id,避免用户信息失效时提交报错
  • 检查ProfileScreen的useEffect,确认退出登录后是否还会触发getUserDetails请求,若有则添加条件判断(比如if (userInfo) dispatch(...))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 17:12:51