繁体   English   中英

父状态更改时,子组件未更新

[英]Child component is not updating when parent state changes

我有一个处于阵列状态的父组件,该阵列也会随着时间的推移而添加。

这是父母。 里面有很多事情,但是我将其简化为主要的状态,即componentShouldUpdate函数(对组件需要执行的其他所有工作)和show data方法也可以工作(我可以确认gaitStats确实正确更新)。

  class GaitMeasure extends Component {
  constructor(props) {
    super(props);

    this.state = {
      grabData: null;
      gaitStats: []
    };
  }  
  shouldComponentUpdate(nextProps) {
   if (this.props.data !== null) {
     if (this.props.data !== nextProps.data) {
       this.showData();
    }
      return false;
    }
   if (this.props.canvas.x !== null) {
     return true;
   } 
  if (this.state.grabData) {
    return true;
  }

  return false;
}

showData() {
....

const avgGait = [...this.state.gaitStats];

avgGait.push(Math.abs(rightX - leftX));

this.setState({
  timeline: this.state.timeline + 3,
  gaitStats: avgGait
});

// render

GaitStat,孩子:

class GaitStat extends Component {
  constructor(props) {
    super(props);
  }


  render() {
    return (
      <div>
        Hi
        <p>{this.props.gaitStats}</p>
      </div>
    );
  }
}

据我所知,在初始渲染之后, this.state.gaitStatus永远不会将this.state.gaitStatus渲染为道具。 无论父对象重新渲染或更新其状态多少次,该prop仍为空数组。

您的shouldComponentUpdate方法可防止类在状态更改时进行更新。 您应该将您的shouldComponentUpdate方法更新为以下内容

shouldComponentUpdate(nextProps, nextState) {
   if(nextState !== this.state){
        return true;
   }
   if (this.props.data !== null) {
     if (this.props.data !== nextProps.data) {
       this.showData();
    }
      return false;
    }
   if (this.props.canvas.x !== null) {
     return true;
   } 
   if (this.state.grabData) {
     return true;
   }

  return false;
}

您可以在此处找到有关shouldComponentUpdate的更多信息。

您可以在子组件中尝试

shouldComponentUpdate(nextProps, nextState) { 
  if(nextProps.gaitStats != this.props.gaitStatus) {
   this.forceUpdate();
 }
}

尝试这个:

 shouldComponentUpdate(nextProps) {
   if ((this.props.data === null && this.props.data !== nextProps.data) || this.props.canvas.x !== null || this.state.grabData) {
        return true;
      }
  this.showData();
  return false;
}

这包括您所有要渲染的条件,如果满足条件则运行showData并返回false,例如不更新

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM