5

我试图将存储在该州的数组中的所有卡路里加起来。

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

4

3 回答 3

9

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

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

于 2019-01-10T03:38:15.313 回答
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

于 2019-01-10T03:44:24.647 回答
2

你可以使用 yourArray.reduce 如下图所示:给定这个数组在 ReactJs

const  App = () => {
  const course ='Half Stack application development'
  const empObj =[
    {
      employeename: 'Ndichu Kabata',
      salary: 10000
    },
    {
      employeename: 'George Githui',
      salary: 70000
    },
    {
      employeename: 'Super Omondi',
      salary: 40000
    }
] 
return (
    <div > 
     <Total  employees={empObj } />
    </div>
  );
}

你需要计算总工资。执行以下操作:

const Total =(props) =>{
  const numbers = props.employees;
  const saloTotal = numbers.reduce((totalHolder,m) => totalHolder + m.salary,0);
  return(
        <>
           <p>Total Salary:  {saloTotal}</p>
        </>
  )}
于 2021-09-29T06:41:20.637 回答