簡體   English   中英

react - 當 props 值相同時強制 componentDidUpdate()

[英]react - force componentDidUpdate() when props are same value

在我的組件中,我試圖將接收到的 props 與當前狀態同步,以使其從外部可見(我知道這是一個反模式,但我還沒有想出另一個解決方案。我非常願意接受建議!)。

無論如何,這就是我所擁有的:

export class PopupContainer extends React.Component {
  state = {
    show: false,
  };

  shouldComponentUpdate(nextProps, nextState) {
    if (this.props.show === nextProps.show) return true;
    return true;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // if popup shown, fade it out in 500ms
    if (this.props.show !== prevProps.show)
      this.setState({ show: this.props.show });

    if (this.state.show) {
      setTimeout(() => this.setState({ show: false }), 2000);
    }
  }

  render() {
    return <Popup {...{ ...this.props, show: this.state.show }} />;
  }
}

在我的外部組件中,我正在渲染容器:

<PopupContainer
          show={this.state.popup.show}
          message={this.state.popup.message}
          level={this.state.popup.level}
        />

現在,當我最初將this.state.show設置為true它可以工作,但是每個連續的賦值也是true中間沒有任何false賦值不起作用。 即使道具的值相同,我如何強制componentdidUpdate()觸發? shouldComponentUpdate()似乎沒有解決問題。

謝謝!

編輯:我注意到render()方法僅在父元素中調用。 似乎因為 child 的屬性沒有變化,react 甚至不會費心重新渲染 childern,這在某種程度上是有道理的。 但是我怎么能強迫他們重新渲染呢?

這是一種黑客行為,但它對我有用。

在兒童班

在構造函數中添加一個要狀態的屬性 - 我們稱之為myChildTrigger ,並將其設置為空字符串:

this.state = {
   ...
   myChildTrigger: ''
}

然后將此添加到componentDidUpdate

componentDidUpdate(prevProps) {
   if(this.state.myChildTrigger !== this.props.myParentTrigger) {

      // Do what you want here

      this.setState({myChildTrigger: this.props.myParentTrigger});
   }
}

在父類

在構造函數中添加一個myParentTrigger來聲明:

this.state = {
   ...
   myParentTrigger: ''
}

在 render 方法中,將其添加為 prop,如下所示:

<ChildClass ... myParentTrigger={this.state.myParentTrigger} />

現在您可以觸發對componentDidUpdate的調用以執行 if 語句中的任何內容,只需將myParentTrigger設置為一個新值,例如:

this.setState({ myParentTrigger: this.state.myParentTrigger + 'a' });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM