簡體   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