【问题标题】:react not updating child components visually after setstate在 setstate 之后反应不更新子组件
【发布时间】:2021-03-27 04:49:44
【问题描述】:

删除子组件上的“违规”后,我更新了父组件中的状态,但是更改并没有在视觉上更新。在它更新的状态下,不会刷新子组件。这可能与浅层更新有关,但我不确定如何修复它。

我的 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);
};

【问题讨论】:

  • 您能分享一下您所在州的样子吗?

标签: javascript reactjs react-component


【解决方案1】:

当你的 nextState 依赖于旧的时,你应该像这样传递一个函数来更新你的状态:

  this.setState((prevState, props) => {
            return {
               students:  prevstate.students.map((student) => {
                   return {
                    ...student,
                    infractions: student.infractions.filter((infraction) => infraction.id !== id;),
                   };
              });
            };
   });

【讨论】:

  • 这样试了,结果一样,没有更新子组件但是状态还在更新
【解决方案2】:

setState 是一个异步函数。 试试这个:

 this.setState({
     students: updatedData, 
 },() => {
     console.log(this.state.students);
 });

【讨论】:

  • 是的,它是异步的,但它仍然没有更新子组件
猜你喜欢
  • 2018-07-17
  • 1970-01-01
  • 1970-01-01
  • 2021-03-23
  • 2020-05-06
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多