简体   繁体   English

为什么我对(this.ingredients)没有定义?

[英]why I am getting undefined for the (this.ingredients)?

I am trying to log the ingredients to the console but it is always undefined我正在尝试将成分记录到控制台,但始终未定义

export default class Recipe {
    constructor(ID) {
        this.ID = ID;
    }

    getRicepeById () {
        const res = await fetch(`https://www.food2fork.com/api/get?key=${key}&rId=${this.ID}`);
        this.title = res.data.recipe.title;
        this.image = res.data.recipe.image_url;
        this.author = res.data.recipe.publisher;
        this.ingredients = res.data.recipe.ingredients; 
        //this.ingredients = [1, 2, 3, 4, 4, 23, 2];
    }

    calculateTime() {
        const totalIngredients = this.ingredients;
        //here is my problem
        console.log(totalIngredients)
    }
}

getRicepeById should be async because you use await in the body of this method. getRicepeById应该是async的,因为您在此方法的主体中使用了await Also, make sure you are calling calculateTime after fetch completed另外,请确保在fetch完成后调用calculateTime

and you have to read the fetched data as follow:并且您必须按如下方式读取获取的数据:

 class Recipe { constructor(ID) { this.ID = ID; } async getRecipeById () { const res = await fetch(`https://api.myjson.com/bins/jta0q`); res.json().then(data => { this.ingredients = data; this.calculateTime(); }); } calculateTime() { const totalIngredients = this.ingredients; console.log(totalIngredients) } } let recipe = new Recipe(); recipe.getRecipeById();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM