前端错误-null结构

让我分析一下当 datanull 时会发生什么。 Ran tool 当 datanull 时,让我逐行分析可能发生的错误:

  1. 这里:allClasses.current = data?.class_students || [];

    • 如果 datanulldata?.class_students 会返回 undefined
    • 由于使用了 || [],这里会被赋值为空数组 []
    • 这行不会出错
  2. 这里:const { active, disable } = data?.class_students?.reduce(...)

    • 如果 datanulldata?.class_studentsundefined
    • undefined?.reduce(...) 会返回 undefined
    • 这会导致解构赋值错误TypeError: Cannot destructure property 'active' of 'undefined' as it is undefined.

让我查看这个函数的完整上下文,确认我的分析: Read file: /Users/chenyao/myProjects/teacher-web/src/pages/SchoolManage/component/MistakeStudent/index.tsx Ran tool

分析结果

datanull 时,会在 第83行 发生错误:

具体错误:

javascript 复制代码
const { active, disable } = data?.class_students?.reduce(...)
  • 如果 datanulldata?.class_students 返回 undefined

  • undefined?.reduce(...) 也返回 undefined

  • 尝试从 undefined 中解构 { active, disable } 会抛出:

    javascript 复制代码
    TypeError: Cannot destructure property 'active' of 'undefined' as it is undefined.

为什么会出错:

  1. 可选链操作符 ?. 只是避免了在 null/undefined 上调用方法时的错误
  2. 但是 reduce 方法在 undefined 上调用时返回 undefined
  3. 解构赋值 const { active, disable } = undefined 会失败

修复建议:

javascript 复制代码
const { active, disable } = data?.class_students?.reduce(
  // ... reduce logic
) || { active: [], disable: [] };

或者更安全的写法:

javascript 复制代码
const classStudents = data?.class_students || [];
const { active, disable } = classStudents.reduce(
  // ... reduce logic
  { active: [], disable: [] }
);

这样即使 datanull,代码也能正常执行,activedisable 都会被初始化为空数组。

相关推荐
yinuo41 分钟前
uniapp微信小程序华为鸿蒙定时器熄屏停止
前端
gnip2 小时前
vite中自动根据约定目录生成路由配置
前端·javascript
前端橙一陈3 小时前
LocalStorage Token vs HttpOnly Cookie 认证方案
前端·spring boot
~无忧花开~3 小时前
JavaScript学习笔记(十五):ES6模板字符串使用指南
开发语言·前端·javascript·vue.js·学习·es6·js
泰迪智能科技013 小时前
图书推荐丨Web数据可视化(ECharts 5)(微课版)
前端·信息可视化·echarts
CodeCraft Studio4 小时前
借助Aspose.Email,使用 Python 读取 Outlook MSG 文件
前端·python·outlook·aspose·email·msg·python读取msg文件
家里有只小肥猫5 小时前
react 初体验2
前端·react.js·前端框架
慧慧吖@5 小时前
前端发送请求时,参数的传递格式
前端
L李什么李5 小时前
HTML——使用表格制作简历
前端·javascript·html
未来之窗软件服务5 小时前
万象EXCEL开发(八)excel公式解析与依赖映射 ——东方仙盟金丹期
前端·excel·仙盟创梦ide·东方仙盟·万象excel