React优化

70 阅读1分钟

使用Fragment减少层级

render(){
  return <>
    <p></p>  
    <p></p>  
  </>
}

JSX中不要定义函数

不要这样

<button onClick={()=>{..}}></button>

要这样

class MyComponent extends React.Component{
  clickHandler = () => {}
  render(){
    return <>
      <button onClick={this.clickHandler}></button>
    </>
  }
}

因为jsx会变化很频繁,如果一直频繁去创建函数,就会狠消耗性能

要在构造函数中使用bind

class MyComponent extends React.Component{
  constructor(){
    this.clickHandler2 = this.clickHandler2.bind(this)
  }
  clickHandler2(){}
  render(){
    return <>
     {/* 不要这样,理由跟上一条一样 */}
      <button onClick={this.clickHandler1.bind(this)}></button>
     {/* 要这样 */}
      <button onClick={this.clickHandler2}></button>
    </>
  }
}

sholdComponentUpdate

  • 使用sholdComponentUpdate
  • 或者使用PureComponent
  • 使用React.memo