重置元组数组中的值

时间:2019-06-04 08:30:50

标签: reactjs

我有一个原型电子商务购物车,其中包含要购买的物品和物品数量。有一个项目列表,每个项目都有一个值(要购买的项目数),一个增加按钮和一个删除按钮。我正在尝试添加一个重置按钮,该按钮会将值设置为零。

我已经编写了一个handleReset函数来实现此功能。

state = {
    counters: [
      { id: 1, value: 0 },
      { id: 2, value: 9 },
      { id: 3, value: 2 },
      { id: 4, value: 3 }
    ]
  };

handleReset = () => {
    let counters = [...this.state.counters];
    counters = counters.map((counter, index) => {
      counter.id, 0;
    });
    this.setState({ counters });
  };

/* I need the state to look like this: */

state = {
    counters: [
      { id: 1, value: 0 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };

当我如上所述尝试handleReset时出现错误:

Failed to compile
./src/components/counters.jsx
  Line 29:  Expected an assignment or function call and instead saw an expression  no-unused-expressions

Search for the keywords to learn more about each error.

2 个答案:

答案 0 :(得分:0)

因此,您可以按照以下方式更改handleReset方法,因为在使用map时需要返回:

handleReset = () => {
  let counters = [...this.state.counters];
  counters = counters.map((counter, index) => {
    return {id: counter.id, value: 0};
  });
  this.setState({ counters });
};

或者您也可以将其写为:

handleReset = () => {
  let counters = [...this.state.counters];
  counters = counters.map((counter) => ({id: counter.id, value: 0}));
  this.setState({ counters });
};

答案 1 :(得分:0)

您的handleReset应该看起来像这样:

handleReset = () => {
  const newCounters = this.state.counters.map(counter=>
    ({id: counter.id, value: 0})
  )
  this.setState({counters: newCounters})
};

也尝试制作不可变的方法,如此处所述:Why is immutability so important (or needed) in JavaScript?