简体   繁体   中英

reactjs - how to switch on and off updates in a child component?

I have a ReactJS that uses a child component that updates when it does not need to.

I want to control when that child updates by providing it with my own shouldComponentUpdate function. Can this be done and how?

Please note the comments below refer to the first version of this question which did not at all reflect the original problem and the solution that the discussion led to.

UPDATE: this is not the right way to solve the original problem that I had. Whilst Kyle's answer is correct, the right way to solve it is to wrap the component that is rerendering too much in a higher order component that implements its own shouldComponentUpdate function.

@Kyle Richardson gets the credit for this answer. It works beautifully!

To illustrate Kyle's solution, two buttons that switch off updates in a child component and switch them back on again.

The assumption here is that you have refs to the child component (in this case this.refs.table)

  <button
    onClick={() => {if (!!this.refs.table) {this.refs.table.shouldComponentUpdate = () => true}}}>
    child component updates on
  </button>
)

  <button
    onClick={() => {if (!!this.refs.table) {this.refs.table.shouldComponentUpdate = () => false}}}>
    child component updates off
  </button>

Be aware that this will clobber any existing shouldComponentUpdate function. You could probably somehow extend/override/compose the existing function but in my case I do not care because there is no existing shouldComponentUpdate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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