我想问一下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/