在 React JSX 中显示值的总和

Displaying the Sum of values in React JSX

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

  id: shortid.generate(),
  text: this.state.text,
  calorie: this.state.calorie

这是状态数组meals中存储的数据结构

我目前 运行 一个 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 中显示膳食中的总卡路里

reduce是一个数组函数,不是饭对象函数。尝试用 reduce 替换 forEach

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

第一个 reduce 假设卡路里是数字,第二个是 if strings

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

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

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

希望对您有所帮助。

更新 - 当您尝试从膳食对象数组计算卡路里时,我们可以按如下方式进行 -

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

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

您可以使用 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>
        </>
  )}