TypeError: Cannot read properties of undefined (reading 'product')”

TypeError: Cannot read properties of undefined (reading 'product')”

我正在尝试读取 Shopify 的 post-购买脚本中的 Shopify 产品页面标签和 ID。

你不需要熟悉 Shopify 就能理解我面临的这个问题。这感觉是一个 Javascript 问题,我无法准确理解如何引用这些变量或对象。

请阅读有关我可以访问的变量的 Shopify 文档 here

我的代码

// Cart variables
var cartTagsString = "";
var cartProductIDString = "";

// Convert array of product tags into string
window.Shopify.order.lineitem.product.tags.forEach(function (item, index) {
cartTagsString = cartTagsString + item;
});

// Convert array of product id's into string
window.Shopify.order.lineitem.product.forEach(function (item, index) {
cartProductIDString = cartTagsString + item.id;
});

错误

“VM1370:44 Uncaught TypeError: Cannot read properties of undefined (reading 'product')”

转到发生错误的确切行,它把我们带到这里:

window.Shopify.order.lineitem.product.tags

在这种情况下,文档实际上可能是错误的。

有一个 table 的属性,它有一个叫做 lineItem 的东西(顺便说一下,这与 lineitem 不同,大小写很重要)。但是 代码示例 显示一个名为 lineItems 的 属性。甚至在那 table 中,它 lineItem 描述为“订单的行项目”,这意味着一个数组。

根据代码示例,您的 forEach 将是这样的:

window.Shopify.order.lineItems.forEach(function (item, index) {
    cartTagsString = cartTagsString + item.id;
});

forEach 调用的 中,每个 item 都是该数组中的一个元素。 item 应该有一个名为 product 的 属性 如果您需要访问它。


至于你对 forEach 的第一次调用,我在该页面上没有看到任何包含 tags 属性 的内容。但是结构是一样的。例如,如果给定的 item 有一个 tags 数组,那么您将访问 item 的数组。例如:

window.Shopify.order.lineItems.forEach(function (item, index) {
    cartTagsString = cartTagsString + item.id;
    item.tags.forEach(function (tag) {
        // do something with the tag
    });
});

您可以联系供应商,要求他们澄清文档。但是作为一个调试步骤,如果所有其他方法都失败了,你总是可以 console.log 一个对象来观察它有什么属性。文档是人写的,人也会犯错。 (或者可能是由母语不是文档语言的人编写的,可能会不时混淆语法。)