解构前必须用 || {} 或 ?? {} 为顶层对象兜底,嵌套结构需逐层设默认空对象,深层取值优先用可选链 ?.,后端返回 null 时需先归一化再解构。

直接给解构目标加空对象兜底,再配合嵌套默认值,就能避免父级为 null 或 undefined 时崩溃。
必须用 || {} 或 ?? {} 兜住顶层对象
解构前不保护原始对象,遇到 null 会直接报错:Cannot destructure property 'xxx' of 'obj' as it is null。所以第一步永远是确保解构源是个对象:
-
const { name, age } = user || {};—— 最常用,兼容null和undefined -
const { name, age } = user ?? {};—— 语义更精准,只对null和undefined生效 - 别写
const { name } = user;(user为null时必崩)
嵌套结构要逐层设默认空对象
光兜顶层不够,中间某一层是 null(比如 user.profile === null),深层解构仍会失败。正确做法是每层都提供默认值:
使用约定式提交(Conventional Commits)生成标准化的 Git 提交信息。适用于以下场景: (1) 暂存更改时需要提交信息; (2) 审查 diff 时希望获得结构化摘要; (3) 编写 PR 描述或变更日志(changelog)条目; (4) 用户明确要求“为本次更改编写提交信息”。 该功能会分析已暂存/未暂存的 diff,并生成按类型(type)划分范围的提交信息。
- 两层嵌套:
const { profile = {} } = user || {};,再解构profile - 一步到位(可读性略低但可行):
const { profile: { name, avatar } = {} } = user || {}; - 三层及以上建议拆开写,例如:
const { data = {}, meta = {} } = res || {};,再分别处理
用可选链 ?. 配合解构取值更安全
当只需取某个深层字段、不需解构整块结构时,可选链比嵌套解构更轻量、容错更强:
const name = user?.profile?.name || '游客';const avatarUrl = user?.profile?.avatar?.url ?? '/default.png';- 它天然跳过
null/undefined,不需要手动每层设默认值
后端返回 null 字段时,优先用 ?? 归一化
解构默认值({ avatar = '/default.png' })对 null 不生效,所以得先清理数据:
- 先归一化:
const safeUser = { ...user, avatar: user?.avatar ?? '/default.png' }; - 或封装清洗函数:
const cleanUser = (u) => ({ ...u, profile: u?.profile ?? {} }); - 再解构:
const { profile: { name, city } } = cleanUser(user);










