React关于上下文this的最佳实践

用户名

关于React类组件中的性能,以下哪一项是最佳实践:

  1. 在构造函数中绑定一个回调函数:

    constructor(props)
    {
        /* some code */
        this.onChange= this.onChange.bind(this)
    }
    
    render() {
       return(
          <div>
              <input onChange={this.onChange}
          </div>
       );
    }
    
    onChange(event) {
    /* some code involving 'this' */
    }
    
  2. 使用箭头功能代替普通功能:

    constructor(props)
    {
        /* some code */
    }
    
    render() {
       return(
          <div>
              <input onChange={this.onChange}
          </div>
       );
    }
    
    onChange = (event) => {
    /* some code involving 'this' */
    }
    
  3. 坚持正常的功能,但在onChange字段中声明了箭头功能:

    constructor(props)
    {
        /* some code */
    }
    
    render() {
    <div>
        <input onChange={(event) => {this.onChange(event)}}
    </div>
    }
    
    onChange(event) {
    /* some code involving 'this' */
    }
    

谢谢!

nem035

关于this所有3个选项的行为都相同。

选项3在每个渲染上创建一个新功能,因此不如选项1和2所期望(因为这样的重新创建是不必要的,并且可能会阻碍性能)

就选项1和2而言,它们归结为相同的行为,而与的行为无关this

了解它们为什么会表现相同的技巧this是知道以下代码的作用:

method = () => {}

向实例添加方法只是语法糖:

class A {
  method = () => {}
}

// is the same as

class A {
  constructor() {
    this.method = () => {}
  }
}

看看Babel是如何进行转换的

由于箭头函数继承了定义this的上下文,因此选项2的上下文是类本身。

class A {
  constructor() {
    this.method = () => {
      return this;
      //     ^^^^ this points to the instance of A
    }
  }
}

const a = new A();
console.log(a.method() === a); // true

选项1的含义相同:

class A {
  constructor() {
    this.method = this.method.bind(this);
  }
  method() {
    return this;
    //     ^^^^ this points to the instance of A
  }
}

const a = new A();
console.log(a.method() === a); // true

这意味着您的选择取决于以下两者之间的区别:

// option 1
constructor(props) {
  this.onChange = this.onChange.bind(this)
}

onChange() {
 // code for onChange...
}

// option 2
constructor(props) {
  this.onChange = () => /* code for onChange */
}

我将给选项1的主要优点是,它具有命名函数而不是箭头函数,这使得在检查堆栈跟踪时调试变得更加容易(尽管函数名推断会稍微减少这一点)。

我会给选项2的主要优点是,它看起来有点“干净”,就像不太冗长的代码一样,但这是一个主观的观点。

总体而言,选项1和选项2实际上没有区别。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章