Javascript 无法读取属性';长度';未定义的…尽管对象已定义
首先,我有以下代码部分:Javascript 无法读取属性';长度';未定义的…尽管对象已定义,javascript,Javascript,首先,我有以下代码部分: export default class Recipe { constructor(recID) { this.RecipeID = recID; } async GetRecipe() { try { let Result = await Axios( `https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}` );
export default class Recipe {
constructor(recID) {
this.RecipeID = recID;
}
async GetRecipe() {
try {
let Result = await Axios(
`https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}`
);
this.Tilte = Result.data.recipe.title;
this.Author = Result.data.recipe.publisher;
this.Image = Result.data.recipe.image_url;
this.Url = Result.data.recipe.source_url;
this.Ingredients = Result.data.recipe.ingredients;
this.PublisherUrl = Result.data.recipe.publisher_url;
this.Rank = Result.data.recipe.social_rank;
} catch (error) {
alert(error);
}
}
CalculateTime() {
try {
this.Time = Math.ceil(this.Ingredients.length / 3) * 15; // error is here
} catch (error) {
console.log(this.RecipeID + ": Length Error->"+error);
}
}
}
然后在单独的文件中调用上述代码,如:
import Recipe from "./Recipe";
const RecipeController = async () => {
const ID = window.location.hash.replace("#", "");
if (ID) {
AppState.Recipe = new Recipe(ID);
try {
await AppState.Recipe.GetRecipe();
AppState.Recipe.CalculateTime();
console.log(AppState.Recipe);
} catch (error) {
alert(error);
}
}
};
现在,如下图所示,我确实得到了请求的响应&承诺已得到解决,加上“配料”数组中有元素,但有时在调用“CalculateTime()时仍会出现错误“无法读取未定义的属性'length'”'虽然现在已经定义了数组,而且有时我没有收到任何错误&它工作得非常好。为什么会出现这种随机行为?即使是JSON响应中的id&我记录的错误也与之匹配,即47746。
你确定一些回答没有遗漏成分吗?计算时间总是在getRecipe之后调用 我会添加一个条件或回退来防止错误,如中所示
this.Time = Math.ceil((this.Ingredients || []).length / 3) * 15;
这就是为什么有太多的
try
/catch
es会掩盖错误的原因,从而导致调试困难的原因之一。问题可以归结为以下几点:
类配方{
构造函数(recID){
this.RecipeID=recID;
}
异步GetRecipe(){
让结果=等待获取(
`https://forkify-api.herokuapp.com/api/get?rId=47746`
)。然后(res=>res.json());
console.log(Result);//我推测这种“随机”行为可能与异步代码有关。在计算之前,您需要确保类具有适当的成分。我觉得您应该尝试使用.then()
和.catch()将语法更改为
,尤其是因为您已经在代码中使用了try/catch
。这种方法将确保正确解析axios请求的承诺,并消除“随机性”,因为您可以更好地控制承诺处理的不同阶段
let Result = await Axios(
`https://forkify-api.herokuapp.com/api/get?rId=${this.RecipeID}`
)
.then((data) => {
this.Tilte = data.data.recipe.title;
this.Author = data.data.recipe.publisher;
this.Image = data.data.recipe.image_url;
this.Url = data.data.recipe.source_url;
this.Ingredients = data.data.recipe.ingredients;
this.PublisherUrl = data.data.recipe.publisher_url;
this.Rank = data.data.recipe.social_rank;
this.Ingerdients = data.data.recipe.ingredient;
}
.catch((err) => {
console.log(err);
return null;
});
将console.log(Result.data.recipe.components)
添加到GetRecipe()