Attention should be paid to the hidden dangers of bind of this when react realizes pure render!

  • 2021-08-03 08:36:54
  • OfStack

I won't say much about pure render, but I attach another article linking how to maximize the performance of react (prequel)

Whether you use immutable or not, as long as you want to achieve pure render, the following is worth your attention!

One day, I was the same as usual. I wrote react happily and used @ pureRender.


export default class extends Component {
...
 render() {
  const {name,age} =this.state;
  return (
   <div>
    <Person name={name} age={age} onClick={this._handleClick.bind(this)}></Person>//bug  Where 
   </div>
  )
 }
...
}

A problem was found. For the child component Person, when the parent component re-render, even if the two props before and after Person did not change, it would still be re-render, even if immutable. js was not easy to use.

It turns out that every time the parent component render, _ handleClick will execute bind (this), so the reference of _ handleClick will be changed every time, so props before and after Person is actually different.

So what should I do? Remove bind (this)? No, you have to use it

The real answer is to let the parent component not execute bind (this) every time render, and directly execute it in advance after constructor is modified


export default class extends Component {
 constructor(props){
  super(props)
  this._handleClick=this._handleClick.bind(this)// Change it to this 
 }
 render() {
  const {name,age} =this.state;
  return (
   <div>
    <Person name={name} age={age} onClick={this._handleClick}></Person>
   </div>
  )
 }
...
}

Reference: React. js pure render performance anti-pattern


Related articles: