zoukankan      html  css  js  c++  java
  • React性能优化

    单组件

    每次修改state都会重新执行render,bind,箭头函数每次render都会执行一次,会重新生成一个新的函数

    case1

    render() {
        console.log('render')
        return (
          <div>
            <div>{this.state.num}</div>
            <button onClick={this.handlerClick.bind(this)}>Click1</button>
            <button onClick={() => this.handlerClick()}>Click2</button>
          </div>
        )
      }
    
      handlerClick() {
        console.log('handlerClcik')
        this.setState({num: this.state.num + 1})
      }

    推荐写法

    constructor(props) {
        super(props)
        this.state = { num:0}
        this.handlerClick = this.handlerClick.bind(this)
      }
    
    
    <button onClick={this.handlerClick}>Click0</button>

    这个案例如果直接内联写样式也是不推荐,每次render也会重新生成一个新对象{color:'red’}

    case2:

    <div style={{color:'red'}}>{this.state.num}</div>

    shouldComponentUpdate

    两个参数nextProps,nextState

    if(nextProps.title===this.props.title) {return false}
    return true

    每次父组件state,props发生变化都会重新渲染子组件render函数

    如果state发生变化渲染子组件render函数会影响性能,可以通过PureComponent进行性能优化

    immutable

    可以提升性能,因为不可变数据结构

    reselect

    可以做缓存

    key 

  • 相关阅读:
    uva514Rails(栈)
    hdu1160FatMouse's Speed
    如何截取整个屏幕
    equals 与==
    (转载)equals与==
    (转载)关于ArrayList的5道面试题
    java的一些程序
    (转载)OSI七层参考模型和TCP/IP四层参考模型
    (转载)算法面试题
    (转载)火车运煤
  • 原文地址:https://www.cnblogs.com/sonwrain/p/10796294.html
Copyright © 2011-2022 走看看