在React JSX中显示值的总和

时间:2019-01-10 03:33:25

标签: javascript reactjs methods components high-order-component

我正在尝试将数组中存储在状态中的所有卡路里加起来。

  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显示膳食中的总热量

2 个答案:

答案 0 :(得分:3)

Reduce是一个数组函数,而不是餐对象函数。尝试将forEach替换为reduce

meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0)

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

const meals = [
  { calorie: 10},
  { calorie: 15},
  { calorie: 20}
];

const calorieTotal = meals.reduce((totalCalories, meal) => totalCalories + meal.calorie, 0);

console.log(calorieTotal); // 45 calories

const mealsAsStrings = [
  { calorie: '11'},
  { calorie: '12'},
  { calorie: '13'}
];

const calorieStringTotal = mealsAsStrings.reduce((totalCalories, meal) => totalCalories + parseInt(meal.calorie, 10), 0);

console.log(calorieStringTotal); // 36 calories

答案 1 :(得分:2)

您不能在数组元素上使用reduce方法,因为它是数组方法。在上面的示例中,您正在循环进入数组,并尝试对不正确的每个数组元素调用reduce。您可以执行以下操作-

this.state.meals.reduce((accumulator, currentValue) => accumulator + currentValue)

希望有帮助。

更新- 当您尝试从膳食对象数组计算卡路里时,我们可以执行以下操作-

this.state.meals.reduce((accumulator, currentValue)=> accumulator + accumulator, currentValue.calorie,0);

检查链接以了解reduce方法的详细用法- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce