![](/img/trans.png)
[英]Javascript (React + Flow) - Destructuring with nullable nested objects
[英]Nested Destructuring in JavaScript Inside Objects
我需要在我的 React 应用程序的嵌套对象中声明orderItems
。 有时order
为空,因此找不到orderItems
。 所以错误当然是Cannot read property of orderItems of null
。 我该如何解决?
const { order: { orderItems = [] } = {} } = res.cartFind
有时 order 为空,因此找不到 orderItems。
因为它是null
(不是undefined
),所以我们不能用默认值解决它(因为它们只适用于缺少或undefined
东西,特别是)。 但由于它位于res.cartFind
的顶层,我们可以使用nullish 合并来解决它。 删除{order: ....}
部分并将.order
移动到最后,然后默认为?? {}
?? {}
,并解构:
const { orderItems = [] } = res.cartFind.order ?? {};
现场示例:
function example(res) { const { orderItems = [] } = res.cartFind.order ?? {}; console.log(orderItems); } console.log("When order is null:"); example({ cartFind: { order: null, }, }); console.log("When order is not null:"); example({ cartFind: { order: { orderItems: [1, 2, 3], }, }, });
在评论中,我想你已经问过如果order
在那里并且它有orderItems: null
会怎样。 有了上面的内容,您最终会得到null
,因为(再次)默认值仅在缺少某些内容或undefined
时才会使用。
处理undefined
和null
(我们称之为“nullish”值)的两个东西是 nullish 合并(我们在上面使用过), ??
, 和可选的链接, ?.
.
如果order
可能丢失,或者它可能存在但其中orderItems: null
,您可以使用两者的组合来处理它:
const orderItems = res.cartFind.order?.orderItems ?? [];
这是它的工作原理:
res.cartFind.order
为null
或undefined
(或缺失,实际上是undefined
),则res.cartFind.order?.orderItems
导致undefined
(它不会像没有?
order
后)。 如果res.cartFind.order
不是null
或undefined
(nullish),那么我们尝试从中获取orderItems
。res.cartFind.order?.orderItems
已经被评估并给了我们undefined
或orderItems
的值(可能是任何东西)。 通过使用thatResultValue ?? []
thatResultValue ?? []
我们说“如果它不是null
或undefined
,则使用thatResultValue
,但如果是,则使用[]
。”现场示例:
function example(res) { const orderItems = res.cartFind.order?.orderItems ?? []; console.log(orderItems); } console.log("When order is null:"); example({ cartFind: { order: null, }, }); console.log("When order is not null and has a valid orderItems:"); example({ cartFind: { order: { orderItems: [1, 2, 3], }, }, }); console.log("When order is not null but doesn't have orderItems:"); example({ cartFind: { order: { }, }, }); console.log("When order is not null and has orderItems but it's null:"); example({ cartFind: { order: { orderItems: null, }, }, });
.as-console-wrapper { max-height: 100% !important; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.