簡體   English   中英

重新渲染React組件

[英]re-rendering React Component

我有一個react類,需要在其中使用shouldComponentUpdate() ,以防止組件與其父對象之間發生無限循環。

我只是簡單地檢查nextProps的深層克隆是否等於this.props ,並且僅更新不相等的組件。

到現在為止還挺好。 (?)

class Child extends Component {
  onComponentUpdate = (e) => {
    this.props.update(e)
  }
  shouldComponentUpdate(nextProps, nextState) {
    return  JSON.stringify(nextProps) !== JSON.stringify(this.props)
  }
  render() {
    return (
      <div>
        // some code that might trigger onComponentUpdate()
      </div>
    );
  }
}

現在,在我的父組件中,發生了一些事情,使我想在不更改特定道具的情況下重新渲染孩子。 我現在要做的是更改狀態計數器,並將其作為道具傳遞給孩子。 我從不對計數器進行任何操作,這只是指示孩子道具實際發生了變化,以便孩子可以更新。

class Parent extends Component {
  constructor() {
    super()
    this.state = { counter: 0 }
  }
  otherChildChanged = () => {
    this.setState({ counter: this.state.counter + 1 })
  }
  render() {
    return (
      <div>
        <Child
          counter={this.state.counter}
          update={"some function"}
          other={"props"}
        >
        </Child>
        <OtherChild onChange={this.otherChildChanged}>
        </OtherChild>
        // some code that might trigger onComponentUpdate()
      </div>
    );
  }
}

有一個更好的方法嗎?

您應該向下傳遞可調整大小的div的大小,以作為子組件的支持。 這樣,當它更改時, JSON.stringify(nextProps) !== JSON.stringify(this.props)將為true並且將進行重新渲染。

如果某個組件必須根據其父上發生的某些事情以某種方式(例如重新渲染)運行,則應將其作為道具傳遞給它。

暫無
暫無

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

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