前端错误-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 都会被初始化为空数组。

相关推荐
卷帘依旧1 天前
Hooks在Fiber上的存储原理
前端
you45801 天前
学成在线--day02 CMS前端开发(含Vue基础知识得回顾)
前端·javascript·vue.js
xiaofeichaichai1 天前
虚拟 DOM
前端·javascript·vue.js
2401_878454531 天前
前端高频得手写题
前端
初一初十1 天前
vue3实现的纯前端护肤品商城网站
前端·javascript·vue.js·前端框架
卷帘依旧1 天前
React状态管理方案怎么选
前端
zeqinjie1 天前
Flutter 折叠屏 iPad / 宽屏适配实践
android·前端·flutter
小村儿1 天前
连载13- 内部Tools,Claude Code 怎么真正"动"你的代码
前端·后端·ai编程
IT_陈寒1 天前
Python的线程池把我坑惨了,原来异步不是万能的
前端·人工智能·后端
初一初十1 天前
vue3茶叶商城网站vue网页vuejs前端
前端·javascript·vue.js·vscode·前端框架