在 React JSX 中显示值的总和

Sau*_*aul 5 javascript methods components reactjs high-order-component

我试图将存储在状态中的数组中的所有卡路里相加。

  id: shortid.generate(),
  text: this.state.text,
  calorie: this.state.calorie
Run Code Online (Sandbox Code Playgroud)

这是存储在状态数组膳食中的数据结构

我目前正在运行 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>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图在 jsx 中显示膳食中的卡路里总量

Dre*_*ese 8

Reduce是一个数组函数,而不是一个meal对象函数。尝试更换forEachreduce

meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0)
Run Code Online (Sandbox Code Playgroud)

第一个减少假设卡路里是数字,第二个是如果字符串

meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0)
Run Code Online (Sandbox Code Playgroud)