两个相似的反应函数在重新渲染时产生不一致的结果

Two similar react functions produce Inconsistent Results in rerendering

该函数正常运行,组件重新渲染

  handleRemove = (e) => {
//console.log(e);
const arrayCopy = this.state.scanlist.filter((row) => row.ref + row.lot !== e.ref + e.lot);
this.setState({ scanlist: arrayCopy });};

此函数更改状态但组件不会重新呈现

  handleAdd = (e) => {
//console.log(e);
const index = this.state.scanlist.findIndex((row) => row.ref === e.ref && row.lot === e.lot);
let scancopy = this.state.scanlist;
scancopy[index].qty = scancopy[index].qty + 1;
console.log(scancopy);
this.setState({ scanlist: scancopy });};

有人看到这个问题吗?突变?

在第一种方法中过滤方法 returns 新列表,而在第二种方法中它只是引用状态数组。

在第二种方法中尝试浅拷贝,

let scancopy = [...this.state.scanlist]

简单的深拷贝方法,

let scancopy = JSON.parse(JSON.stringify(this.state.scanlist));

使用 Array.prototype.filter 从数组中删除一个元素是非常标准的,但是在第二个处理程序中,是的,你有一个状态对象突变。

handleAdd = (e) => {
  const index = this.state.scanlist.findIndex((row) => row.ref === e.ref && row.lot === e.lot);
  let scancopy = this.state.scanlist;
  scancopy[index].qty = scancopy[index].qty + 1; // <-- state object mutation
  this.setState({ scanlist: scancopy });
};

您应该浅拷贝 scanlist 数组 正在更新的元素。 Array.prototype.map是一种常用的浅拷贝状态数组的方法,将需要更新的元素的对象属性进行浅拷贝。任何时候更新任何嵌套状态对象时,都应该浅复制父对象。

handleAdd = (e) => {
  this.setState(prevState => ({
    scanlist: prevState.scanlist.map(
      (row) => row.ref === e.ref && row.lot === e.lot ? {
        ...row,
        qty: row.qty + 1,
      } : row)
  }));
};