我试图将存储在该州的数组中的所有卡路里加起来。
id: shortid.generate(),
text: this.state.text,
calorie: this.state.calorie
这是存储在状态数组餐点中的数据结构
我目前正在运行一个 forEach 并使用 reducer 将值相加,但它说“reduce”不是一个函数我不确定我做错了什么。
class App extends Component {
state = {
meals: []
};
addMeal = meal => {
this.setState({
meals: [meal, ...this.state.meals]
});
};
onDelete = id => {
this.setState({
meals: this.state.meals.filter(meal => meal.id !== id)
});
};
render() {
return (
<div className="container">
<div className="jumbotron">
<h2>Calorie Counter</h2>
<hr />
<Form onsubmit={this.addMeal} />
<table className="table table-striped">
<thead>
<tr>
<th>Meal</th>
<th>Calories</th>
<th />
</tr>
</thead>
<tbody>
{this.state.meals.map(meal => (
<Meal
key={meal.id}
meal={meal}
onDelete={() => this.onDelete(meal.id)}
/>
))}
<tr>
<td>Total:</td>
<td>
{this.state.meals.forEach(meal =>
meal.reduce(function(y, x) {
return y + x;
}, 0)
)}
</td>
<td />
</tr>
</tbody>
</table>
</div>
</div>
);
}
}
我试图在 jsx 中显示膳食中的卡路里总量