我遇到过一个以前在这里被问过的问题,但我无法找到我做错了什么,或理解原因,或应用其他人的解决方案。所以请多一点耐心并指导我,因为我快要失去理智了。
我正在从 jQuery 切换到 JS,并且正在做一些 API/JSON 练习。我已经成功地完成了在整个网络中找到的常见 WeatherMapAPI 和 RandomUserAPI 示例,遵循代码并在这里和那里进行了一些小的更改。然后我自己生成了一些数据(基于测试 Shopify 商店)并尝试抓取 JSON。
假设我有一些数据,例如:
{
"totalCollections": 172,
"totalProducts": 2752,
"....": ".....",
"...": "...."
"..": ".."
etc
}
然后我正在做:
function getPaginationData() {
const paginationEndpoint = '/endpoint-url';
fetch(paginationEndpoint)
.then(response => {
return response.json();
})
.then(data =>{
console.log(data);
})
.then(data =>{
const asdf = data.totalCollections;
console.log(asdf);
});
}
getPaginationData();
所以我收到错误“未捕获( promise 中)TypeError:无法读取未定义的属性“totalCollections””。
我已经看到了各种其他线程并尝试了各种解决方案,但我没有设法找到解决方案或理解为什么会出现此错误。基本上,我的解决能力已经完全退化了。
为什么我会收到这个?
~~~~~~~~~~~< em>~~_~
编辑 突破(?)
所以我发现在收到响应后我必须创建一个空对象来存储所有数据。所以
const paginationObject = {}; //create empty obj
function getPaginationData() {
const paginationEndpoint = '/endpoint-url';
fetch(paginationEndpoint)
.then(response => {
return response.json();
})
.then(data =>{
console.log(data);
//update my new object with the JSON data
paginationObject.numOfCollections = data.totalCollections;
paginationObject.numOfProducts = data.totalProducts;
.....
....
...
})
.then(function(){
// i can call a function here, for example:
doHTML();
});
}
function doHTML() {
document.querySelector('.element').innerHTML = `${paginationObject.numOfCollections}`;
}
getPaginationData();
这条路正确吗?
最佳答案
我假设您的 console.log(data)
正常工作并且您可以看到您的数据。
.then(data =>{
console.log(data);
})
如果是这种情况...您可以在同一个 .then()
下完成所有操作,并消除使用多个 Promise 的问题。
.then(data =>{
console.log(data);
const asdf = data.totalCollections;
console.log(asdf);
})
希望这能起到作用😊
关于javascript - 无法理解为什么它给我 : Uncaught (in promise) TypeError: Cannot read property 'blabla' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58203937/