[英]Svelte: Promise { <pending> } Cannot read property 'edges' of undefined
Hello someone know why i have this error please?你好有人知道为什么我有这个错误吗?
Promise { } Cannot read property 'edges' of undefined Promise { } 无法读取未定义的属性“边缘”
<script>
import { getProduct } from '../lib/store';
const productId = 'a';
const product = getProduct(productId);
$: console.log(product);
let quantity = 0;
let price = 0;
let total = 0;
$: quantity = quantity < 1 ? 1 : quantity;
$: options = product.variants.edges.map((items) => {
let list = {};
list.id = items.node.id;
list.color = items.node.selectedOptions[0].value;
list.size = items.node.selectedOptions[1].value;
list.price = items.node.priceV2.amount;
return list;
});
$: console.log(options);
</script>
Datas comes from Shopify API Thank you!数据来自 Shopify API 谢谢!
You are awaiting a promise from the getProduct call, so you need a place for the results of that promise to land, and then you can use them.您正在等待来自 getProduct 调用的 promise,因此您需要一个地方来放置 promise 的结果,然后您可以使用它们。 You are seeing the error because you are trying to access the property
variants
of a promise, which doesn't exist, so JS give back undefined as would be expected.您看到错误是因为您试图访问不存在的 promise 的属性
variants
,因此 JS 按预期返回未定义。 Then you try to access edges
of undefined and get the error.然后你尝试访问未定义的
edges
并得到错误。
One way you can fix this is to do the following:解决此问题的一种方法是执行以下操作:
let product = null;
onMount
method from svelte, and you can use it to run an async method, and await the promise for getProducts, then assign it to the product variable:onMount
方法,您可以使用它来运行异步方法,并等待 getProducts 的 promise,然后将其分配给产品变量:import { onMount } from 'svelte'
.....
onMount(async () => {
products = await getProduct(id);
});
$:options = product ? product.variants.edges.map((items) => {
let list = {};
list.id = items.node.id;
list.color = items.node.selectedOptions[0].value;
list.size = items.node.selectedOptions[1].value;
list.price = items.node.priceV2.amount;
return list;
}) : null;
{#if options}
/* Markup here dependent on options */
{/if}
Now the reactive options
variable will update automatically when product
is reassigned from onMount
, and data and rendering will flow accordingly.现在,当从
onMount
重新分配product
时,反应options
变量将自动更新,并且数据和渲染将相应地流动。
You could possibly use optional chaining instead of the ternary operator that I used, however until product
is reassigned, options
would be undefined instead of null.您可以使用可选链接而不是我使用的三元运算符,但是在重新分配
product
之前, options
将是未定义的,而不是 null。 It's up to you on which to use and both ways will work, but I like to be more explicit with null instead of trusting the compiler to come up with the undefined value.这取决于您使用哪种方法,两种方法都可以使用,但我喜欢更明确地使用 null,而不是相信编译器会提供未定义的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.