javascript - React 中关于上下文 `this` 的最佳实践

标签 javascript reactjs performance this arrow-functions

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

  1. 在构造函数中绑定(bind)回调函数:

    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' */
    }
    

谢谢!

最佳答案

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

选项 3 在每个渲染器上创建一个新函数,因此不如选项 1 和 2 理想(因为这种重新创建是不必要的并且可能会影响性能)

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

理解为什么它们与 this 的行为相同的技巧是了解以下代码的作用:

method = () => {}

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

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

// is the same as

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

看看如何Babel transpiles it .

自箭头函数inherits the context it is defined in作为 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 的主要优点是它有一个命名函数而不是箭头函数,这使得在检查堆栈跟踪时调试更容易一些(尽管 function name inferences 稍微淡化了这一点)。

我认为选项 2 的主要优点是它看起来有点“干净”,因为代码不那么冗长,但这是一个主观意见。

总体而言,选项 1 和选项 2 几乎没有区别。

关于javascript - React 中关于上下文 `this` 的最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48385848/

相关文章:

javascript - 为什么 Kendo UI destroy 方法会删除所有子部件?

javascript - JS中的换行\n问题

javascript - 如何使用 React Hooks 处理 React Svg 拖放

reactjs - 我应该在哪里发送我的 redux

node.js - 尝试导入错误 : 'createLocation' is not exported from 'history'

javascript - 如何撤消对未同步集合的更改?

javascript - 使某些 JS 代码比另一个更重要(鼠标移开时消失)

java - 在什么情况下在 Java 中使用 float 优于 double ?

performance - 在半连续列表的二分搜索上使用二分搜索树有现实世界的理由吗?

c++ - 关于 cpp 中带有 const if inside 的 for 循环的最佳实践