后端接口传来的值可能为undefined怎么办,快使用?. (可选链操作符)

158 阅读2分钟

我们在实际开发时候经常会遇见赋值,但是后端可能为传一个undefined的场景,比如后端传了一个obj.data.name1,但是直接接收赋值可能为为undefined,那前端怎么校验呢

可选链操作符

const token = memberStore.profile?.token

注意这个 ?. 就是可选链运算符

在前端代码里,?. 是可选链操作符,其用途是防止因访问可能不存在的属性而引发错误。

在这段代码里:  const token = memberStore.profile?.token,这里使用可选链操作符有以下几个原因:

防止出现 Cannot read property 'token' of undefined 错误

当 memberStore.profile 的值为 undefined 或者 null 时:

  • 若使用普通的点号访问(memberStore.profile.token),程序会抛出错误,进而使后续代码无法继续执行。
  • 而使用可选链操作符(memberStore.profile?.token),表达式会直接返回 undefined,不会中断程序的运行。

适配异步数据加载场景

在实际的应用当中,memberStore.profile 可能需要通过异步方式获取,例如在用户登录之后才会有值。使用可选链操作符可以确保:

  • 在数据尚未加载完成时,不会因为访问 profile.token 而导致页面崩溃。
  • 能够顺利处理用户未登录的情况,此时 profile 可能为 undefined

示例对比

下面通过代码示例来说明两者的区别:

// 假设 memberStore.profile 未定义

const token1 = memberStore.profile.token;        // 抛出错误:Cannot read property 'token' of undefined 
const token2 = memberStore.profile?.token;       // 返回 undefined,不会报错

常见应用场景

可选链操作符在以下这些场景中经常会用到:

  1. 异步数据加载:像接口返回的数据结构可能不完整的情况。
  2. 条件渲染:在组件中需要处理未定义的 props。
  3. 深度嵌套对象:避免因为中间某个属性不存在而引发错误。

结合空值合并操作符

通常,可选链操作符会和空值合并操作符 ?? 一起使用,以便为未定义的值设置默认值:

const token = memberStore.profile?.token ?? ''; // 若 token 为 undefined,则默认赋值为空字符串

总结

在你的代码里使用 ?. 是一种安全的编程实践,它能够优雅地处理数据可能不存在的情况,增强代码的健壮性,同时避免因未定义的属性访问而导致应用崩溃。