zoukankan      html  css  js  c++  java
  • react 实现pure render的时候,bind(this)隐患

    react 实现pure render的时候,bind(this)隐患

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

    发现一个问题,对于Child这个子组件来说,在父组件re-render的时候,即使Child得前后两个props都没改变,它依旧会re-render。。即使用immutable.js也不好使。。。原来啊,父组件每次render,_handleClick都会执行bind(this) 这样_handleClick的引用每次都会改。。所以Child前后两次props其实是不一样的。。 那怎么办?把bind(this)去掉?不行 还必须得用。真正的答案是 让父组件每次render 不执行bind(this),直接提前在constructor执行好,修改之后

    export default class Parent extends Component {
      constructor(props){
        super(props)
        this._handleClick=this._handleClick.bind(this)//改成这样
      }
      render() {
        const {name,age} =this.state;
        return (
          <div>
            <Child name={name} age={age} onClick={this._handleClick}></Child>
          </div>
        )
      }
    ...
    }

    .

  • 相关阅读:
    osds have slow requests
    supervisor 管理 celery
    guacamole部署
    openstack IPV6
    修复VSAN无法看到主机磁盘
    kolla之docker私有仓库创建
    CSS日食与太阳碰撞
    vue-devtools必备工具
    VUE在BODY上绑定enter事件
    VUE输入框显示时自动聚焦
  • 原文地址:https://www.cnblogs.com/crazycode2/p/9081075.html
Copyright © 2011-2022 走看看