小编Sau*_*aul的帖子

在 React JSX 中显示值的总和

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

  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 …
Run Code Online (Sandbox Code Playgroud)

javascript methods components reactjs high-order-component

5
推荐指数
1
解决办法
2万
查看次数