在setstate之后,react不在视觉上更新子组件



删除一个"违规;在子组件上,我会更新父组件中的状态,但是这些更改不会在视觉上更新。在该状态下,它会更新,但不会刷新子组件。这可能与浅更新有关,但我不确定如何修复它。

我的updatedData也会更新,但状态不会立即更新。

有人能帮我吗?

这是代码

delClick = (id) => {
console.log('id when it come in: ', id);
const updatedData = this.state.students.map((student) => {
return {
...student,
infractions: student.infractions.filter((infraction) => {
return infraction.id !== id;
}),
};
});
console.log('updataed data: ', updatedData);
this.setState({
students: updatedData,
});
console.log('state students: ', this.state.students);
};

当你的下一个状态依赖于旧的状态时,你应该传递一个函数来更新你的状态,如下所示:

this.setState((prevState, props) => {
return {
students:  prevstate.students.map((student) => {
return {
...student,
infractions: student.infractions.filter((infraction) => infraction.id !== id;),
};
});
};
});
setState是一个异步函数。试试这个:
this.setState({
students: updatedData, 
},() => {
console.log(this.state.students);
});

最新更新