【问题标题】:Displaying the Sum of values in React JSX在 React JSX 中显示值的总和
【发布时间】:2019-06-04 21:42:58
【问题描述】:

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

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

【问题讨论】:

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


【解决方案1】:

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

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

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

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

【讨论】:

  • @p.s.w.g 你好,我已经更新并提供了整个代码。我希望它更好
  • 这似乎是连接值而不是添加总和
  • @Saul 如果meal.calorie 是字符串值,它将连接它们。如果是这样,我添加了第二个示例。
【解决方案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

【讨论】:

  • 这非常有帮助,但如果我这样做,reducer 会收到一个空数组,里面包含试图加起来的卡路里
  • 这是正确的膳食数组结构吗? var餐= [{id:1, cal:5}, {id:2, cal:7}, {id:3, cal:9}, , {id:4, cal:10}]
  • 是的 this [{id: "PxCoP4V6B", text: "cheetos", calorie: "100"}] 啊,它看起来像因为它可能将值存储在字符串中?跨度>
【解决方案3】:

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

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 2019-11-14
    • 2022-01-24
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多