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 

  • 相关阅读:
    软件质量见解
    Vim 简明教程【转载】
    Actor Mailbox
    Unity对齐工具
    静态AOP Fody PropertyChanged
    棋牌分布式架构
    死锁
    curl 获取自定义数据
    WPF RichTextBox添加一条有颜色的记录
    arp -s 添加失败:拒绝访问
  • 原文地址:https://www.cnblogs.com/sonwrain/p/10796294.html
Copyright © 2011-2022 走看看