React setState导致UI冻结一两秒钟

时间:2019-07-17 19:17:14

标签: reactjs

我使用一个复选框,其更改状态如下:

<Checkbox
            label="Add to delete list"
            onChange={event => this.handleDeleteCheckboxChange(event, id)}
          />
  handleDeleteCheckboxChange=({ target }, id) => {
    const { deleteMappings } = this.state;

    const check = target.checked;
    if (check === true) {
      const addToExisting = deleteMappings;
      addToExisting.push(id);
      this.setState({ deleteMappings: addToExisting });
    }
    else {
      const removeId = deleteMappings.filter(item => item !== id);
      this.setState({ deleteMappings: removeId });
    }
  }

尽管该复选框和setstate可以按预期工作,但是每当我单击该复选框时,大约需要2秒钟才能更新。 不知道是什么原因造成的,请问对此有何看法。

1 个答案:

答案 0 :(得分:-1)

您能尝试一下吗?

  handleDeleteCheckboxChange=({ target }, id) => {
    const { deleteMappings } = this.state;

    const check = target.checked;
    if (check === true) {
      const addToExisting = [...deleteMappings];
      addToExisting.push(id);
      this.setState({ deleteMappings: addToExisting });
    }
    else {
      const removeId = [...deleteMappings].filter(item => item !== id);
      this.setState({ deleteMappings: removeId });
    }
  }

知道:

const a = [1, 2, 3];
const b = a;
b.push(4);
//b = [1,2,3,4]
//a = [1,2,3,4]
// Assigning `b=a` makes `b` points to the same reference as `a`
// Thus, any changes made on `b` are made to `a`.
// Thus, your old way assigning new array of variables out of the one in your state actually cause mutating the state.

知道:

a= [1,2,3]
b= [...a]
b.push(4);
// b = [1,2,3,4]
// a = [1,2,3]
// [...Array] provides a new copy of an array.
// Thus, any modifications on the new copy wont affect the original value copied from.
// This is called The Spread Syntax as from ES6