无法读取 属性 of null 正在破坏
cannot read property of null doing destructing
析构很酷,但在析构嵌套对象时我开始遇到严重的问题。我有这个代码:
const {
credit: { amont },
} = userProfile
这很危险,因为如果 credit 为空怎么办?整个应用程序中断。我该如何防止这种情况?我知道一种方法是使用 Typescript,但我宁愿不使用。我开始怀疑 destruct for nested 与使用 dot 没有区别。
您可以通过在解构时提供默认值来避免您的应用程序崩溃:
const {
credit: { amont } = {},
} = userProfile
console.log(amont); //amont will be undefined
您以后可以在任何地方使用 !!amont
查看金额。
深度解构无法解决这个问题。正如另一个答案所暗示的那样,可以使用 default values 但它们仅适用于 undefined
值:
const { credit: { amont } = {} } = userProfile || {};
虽然 null
值仍然会导致错误,但有必要对所有可能为空的对象进行短路评估:
const { credit } = userProfile || {};
const { amont } = credit || {};
这可以通过读取路径并检查空值的安全导航实用程序函数来解决。
一个著名的例子是 Lodash get
:
const amont = _.get(userProfile, 'credit.amont');
I know one way is to use typescript but here I don't
只有在保证类型安全的情况下,才有可能使用 TypeScript 解决这个问题。如果 userProfile
来自 JSON 响应,则必须应用运行时类型检查来断言对象不是 null
.
在Javascript中,可以为变量分配默认值,以防从对象/数组中解包的值未定义。
为了避免对象(为空)的深度 de-structuring read-only 属性,您可以像这样分配默认值。在本例中是一个空对象。
析构很酷,但在析构嵌套对象时我开始遇到严重的问题。我有这个代码:
const {
credit: { amont },
} = userProfile
这很危险,因为如果 credit 为空怎么办?整个应用程序中断。我该如何防止这种情况?我知道一种方法是使用 Typescript,但我宁愿不使用。我开始怀疑 destruct for nested 与使用 dot 没有区别。
您可以通过在解构时提供默认值来避免您的应用程序崩溃:
const {
credit: { amont } = {},
} = userProfile
console.log(amont); //amont will be undefined
您以后可以在任何地方使用 !!amont
查看金额。
深度解构无法解决这个问题。正如另一个答案所暗示的那样,可以使用 default values 但它们仅适用于 undefined
值:
const { credit: { amont } = {} } = userProfile || {};
虽然 null
值仍然会导致错误,但有必要对所有可能为空的对象进行短路评估:
const { credit } = userProfile || {};
const { amont } = credit || {};
这可以通过读取路径并检查空值的安全导航实用程序函数来解决。
一个著名的例子是 Lodash get
:
const amont = _.get(userProfile, 'credit.amont');
I know one way is to use typescript but here I don't
只有在保证类型安全的情况下,才有可能使用 TypeScript 解决这个问题。如果 userProfile
来自 JSON 响应,则必须应用运行时类型检查来断言对象不是 null
.
在Javascript中,可以为变量分配默认值,以防从对象/数组中解包的值未定义。 为了避免对象(为空)的深度 de-structuring read-only 属性,您可以像这样分配默认值。在本例中是一个空对象。