javascript - 如何使用 toFixed() 方法

标签 javascript tofixed

我想问一下toFixed()方法及其用法。我有一个叫做卡路里的常量,它是一个数字数据,我想将其四舍五入到小数点后两位。

const recipe = this.state.activeRecipe;
const calories = recipe.calories.toFixed(2);
console.log(calories);

我收到一条错误消息:Uncaught TypeError: Cannot read property 'toFixed' of undefined

有人知道如何解决这个问题或者是否有任何我可以使用的方法?谢谢!

整个代码:

import React, { Component } from "react";

class Recipe extends Component {
    state = {
        activeRecipe: []
    }
    componentDidMount = async() => {
        const title = this.props.location.state.recipe;
        const req = await fetch
        (`https://api.edamam.com/search?q=${title}&app_id=${API_ID}&app_key=${API_KEY}`);

        const res = await req.json();
        this.setState({ activeRecipe: res.hits[0].recipe});
        console.log(this.state.activeRecipe);
        }
        render() {
            const recipe = this.state.activeRecipe;
            const calories = recipe.calories.toFixed(2);
            console.log(calories);
            return (
               <div className="container">
                       <h3 className="active-recipe">{recipe.label}</h3>
                       <div className="container">
                       {recipe.ingredients && recipe.ingredients.map(ingredient => {
                        return (
                            <p>{ingredient.text}</p>

                        );
                       })}
                       </div>
               </div>
            );
        }
}

export default Recipe;

最佳答案

这是一个非常常见的问题。第一次运行 render 时,this.state.activeRecipe.calories 将为空,因为 fetch 调用尚未返回。因此,您需要在 render 函数中考虑到这一点,仅在 this.state.activeRecipe.calories 存在时调用 toFixed:

const recipe = this.state.activeRecipe;
const calories = recipe.calories ? recipe.calories.toFixed(2) : null;

请注意,在这种情况下,您还需要调整 render 函数返回的内容,即您需要知道如果 this.state.activeRecipe 该怎么办> 为空。

关于javascript - 如何使用 toFixed() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59592398/

相关文章:

javascript - 从对象内部的函数访问 this 而无需回调?

JavaScript 在这些语句中会初始化/执行任何内容吗?

javascript - 如何判断 chrome 应用程序正在使用哪个操作系统?

javascript - 使用 "in"运算符搜索 toFixed - "in"运算符如何处理原语?

javascript - 合并具有不同颜色的网格

javascript - 如何获取两个字符串之间的变化(插入、删除或相同)?

javascript - 将 toFixed 添加到现有 Math.abs 函数

javascript - 为什么 (-2.4492935982947064e-16).toFixed(5) 等于 "-0.00000"?

javascript - 寻求帮助将 .toFixed 添加到 jquery。

javascript - 对数组元素使用 toFixed()