Javascript 如何使用toFixed()方法
我想问一下toFixed()方法及其用法。我有一个叫做卡路里的常数,它是一个数字数据,我想把它四舍五入到小数点后2位Javascript 如何使用toFixed()方法,javascript,tofixed,Javascript,Tofixed,我想问一下toFixed()方法及其用法。我有一个叫做卡路里的常数,它是一个数字数据,我想把它四舍五入到小数点后2位 const recipe = this.state.activeRecipe; const calories = recipe.calories.toFixed(2); console.log(calories); 我收到一个错误,说uncaughttypeerror:无法读取未定义的属性“toFixed” 有人知道如何解决这个问题,或者我是否可以使用任何方法?谢谢大家! 整个
const recipe = this.state.activeRecipe;
const calories = recipe.calories.toFixed(2);
console.log(calories);
我收到一个错误,说uncaughttypeerror:无法读取未定义的属性“toFixed”
有人知道如何解决这个问题,或者我是否可以使用任何方法?谢谢大家!
整个代码:
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;
import React,{Component}来自“React”;
类配方扩展组件{
状态={
activeRecipe:[]
}
componentDidMount=async()=>{
const title=this.props.location.state.recipe;
const req=等待取数
(`https://api.edamam.com/search?q=${title}&app_id=${API_id}&app_key=${API_key}`);
const res=wait req.json();
this.setState({activeRecipe:res.hits[0].recipe});
console.log(this.state.activeRecipe);
}
render(){
const recipe=this.state.activeRecipe;
常量卡路里=配方。卡路里。固定(2);
console.log(卡路里);
返回(
{recipe.label}
{recipe.components&&recipe.components.map(component=>{
返回(
{component.text}
);
})}
);
}
}
导出默认配方;
这是一个非常常见的问题。第一次运行render
时,this.state.activeRecipe.carries
将为空,因为fetch
调用尚未返回。因此,如果this.state.activeRecipe.carries
存在,则只需调用toFixed
即可在render
函数中说明这一点:
const recipe = this.state.activeRecipe;
const calories = recipe.calories ? recipe.calories.toFixed(2) : null;
注意,在这种情况下,您还需要调整
render
函数返回的内容,也就是说,如果this.state.activeRecipe
为空,您需要知道该怎么做。正如错误所说,您正试图调用未定义对象的函数属性。您的问题与固定的toFixed
无关;相反,找出recipe.carries
未定义的原因