1

我需要orderItems在我的 React 应用程序中声明一个嵌套对象的内部。有时order为空,因此orderItems找不到。所以错误当然是Cannot read property of orderItems of null。我该如何解决?

 const { order: { orderItems = [] } = {} } = res.cartFind
4

1 回答 1

1

有时 order 为 null,因此找不到 orderItems。

由于它是null(not undefined),我们无法使用默认值来解决它(因为它们仅适用于缺少的东西,或者undefined,特别是)。但由于它位于 的顶层res.cartFind,我们可以使用nullish coalescing来解决它。删除该{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(我们称之为“空值”值)是空值合并(我们在上面使用过)??,和可选链接?.

如果order可能丢失,或者它可能存在但orderItems: null在其中,您可以通过两者的组合来处理:

const orderItems = res.cartFind.order?.orderItems ?? [];

这是它的工作原理:

  1. 如果res.cartFind.ordernullundefined(或缺失,这是有效的undefined),则res.cartFind.order?.orderItems导致undefined(它不会像没有?after时那样抛出错误order)。如果res.cartFind.order 不是 nullundefined(无效),那么我们尝试从中获取orderItems
  2. 所以现在res.cartFind.order?.orderItems已经被评估并给了我们或者(可能是任何东西)undefined的价值。orderItems通过使用thatResultValue ?? [],我们说“thatResultValue如果不是则使用,null或者如果是则undefined使用[]”。

现场示例:

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;
}

于 2021-07-25T09:58:01.340 回答