为什么setState只在原始状态发生变化时更新


interface list {
name: string,
id: number,
marks: number
}

组件状态:

{
listOfStudents: list[],
}

现在,在一些事件中,为具有给定名称和下面的处理程序函数的学生修改了标记,下面的不起作用

currentList = this.state.listOfStudents;
//find the list object with the given name
listToModify = currentList.map(item, ....=> item.name === event.name);
// update its marks
listToModify.marks = event.marks;
//set new state
this.setState({listOfStudents: currentList});

但以下是有效的:

//get a copy of the object
currentList = [...this.state.listOfStudents];
//find the list object with the given name
listToModify = currentList.map(item, ....=> item.name === event.name);
// update its marks
listToModify.marks = event.marks;
//set new state
this.setState({listOfStudents: currentList});

我不需要添加新的数据,而是修改现有的数据,为什么在这种情况下需要突变?

对于对象或数组的给定状态,react只使用其引用进行比较并决定是否更新状态,它不会在对象值之间进行深入比较。

第一种情况是传递相同的引用,因此没有更新状态。实际上,如果您在第一个例子中修改数组,实际上就是直接改变状态。

第二种情况是,您正在克隆到一个新的新鲜数组中,该数组包含不同的引用。由于引用与以前的数组不同,react现在更新其状态。在处理数组/对象时,这实际上是更新状态的正确方法。

最新更新