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

React读取newNotification报错 如何控制通知图标警告角标显隐

报错原因

触发Uncaught TypeError: Cannot read properties of undefined (reading 'newNotification')的核心原因有两个:

  1. 组件首次渲染时,后端接口还未返回数据,notificationData处于undefined状态,直接读取它的newNotification属性就会触发类型错误
  2. 原有实现逻辑存在偏差:给Badge组件加hidden类会直接隐藏整个通知图标(包括可点击的铃铛入口),不符合「始终显示图标、仅无新通知时隐藏角标」的需求;同时CSS嵌套选择器写法有误,.hidden类的样式无法正确生效。
正确实现步骤
  • 初始化通知数据时设置兜底默认值,搭配可选链运算符做安全访问,避免初始渲染报错
  • 使用MUI Badge组件原生提供的*invisible属性*控制角标显隐,无需自定义隐藏类,不会影响通知图标本身的显示和点击
  • 简化CSS代码,移除无用的隐藏类样式,仅保留角标位置、颜色的自定义配置
修正后代码

JSX部分

// 注意:初始化notificationData时务必加默认值,以下为React Hooks写法示例
// const [notificationData, setNotificationData] = useState({ newNotification: false })

<div className="header__notification">
 <AS.Badge 
   color="primary"
   variant="dot"
   onClick={handleNotificationClick}
   // newNotification为false时角标隐藏,其余情况(包括接口加载中)默认显示
   invisible={notificationData?.newNotification === false}
 >
   <AS.NotificationsOutlinedIcon className="header__notification_icon" />
 </AS.Badge>
</div>

CSS部分

.header__notification .MuiBadge-root .MuiBadge-badge {
  background-color: var(--palette-blue-300) !important;
  top: 8px !important;
  right: 7px !important;
}
效果参考

通知角标效果参考

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 09:42:25