【问题标题】:ES6 React: Will ES.Next's @autobind bind methods only once for each instance?ES6 React:ES.Next 的 @autobind 是否会为每个实例只绑定一次方法?
【发布时间】:2016-10-05 09:09:29
【问题描述】:

有很多关于在 ES6 React 中处理绑定的多种方法的问题/文章,但大多数似乎都没有解决React docs 中概述的问题(强调我的):

我们建议您在构造函数中绑定事件处理程序,以便 每个实例只绑定一次:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
  this.tick = this.tick.bind(this);
}

对于上下文,他们建议不要对方法进行内联绑定,例如:

//using .bind()
<div onClick={this.tick.bind(this)}>

// ES6 anon arrow functions
<div onClick={() => this.tick()}>

// ES.Next :: operator
<div onClick={::this.tick}>

当然。但是在构造函数中绑定每个方法的推荐解决方案是繁琐的/很多方法,所以我在看 ES.Next @autobind decorator 在班级级别作为一个简单的解决方案:

import { autobind } from 'core-decorators';

@autobind
class Person {
  getPerson() {
    return this;
  }

  getPersonAgain() {
    return this;
  }
}

let person = new Person();
let { getPerson, getPersonAgain } = person;

getPerson() === person;
// true

getPersonAgain() === person;
// true

我想不通的是:这个装饰器会和内联绑定方法有同样的缺点吗?即,每个实例的方法是否只绑定一次?

如果没有,是否有避免这种陷阱的简洁解决方案?

【问题讨论】:

  • 仅供参考的 ES7 不会有装饰器:2ality.com/2016/01/ecmascript-2016.html
  • 这可能会出现在未来的版本中,但不会出现在 ES7(已经完成)中。请阅读标签维基!我更新了你的问题。

标签: javascript reactjs ecmascript-6 ecmascript-next


【解决方案1】:

Class instance fields 及其关联的初始化程序解决了必须分配与构造函数中的方法同名但语法更简洁的属性的问题。下面的例子可以用 Babel 的class properties transform:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = {count: props.initialCount};
  }
  tick = () => {
    this.setState({count: this.state.count + 1});
  };
  ...
 }

这将为每个 Counter 实例创建一个新的绑定 tick 属性。这将创建与React.createClass 相同的 数量的绑定函数。

没有实例字段和初始化器,效果是一样的(为每个Counter 实例创建一个绑定的tick 属性),但语法更冗长:

constructor(props) {
  super(props);
  this.state = {count: props.initialCount};
  this.tick = this.tick.bind(this);
}
tick() {
  this.setState({count: this.state.count + 1});
}

【讨论】:

  • 这些方法是不等价的:第一种方法,类属性箭头函数,在性能方面有一些缺点,我认为更重要的是测试。有关有趣的文章,请参阅 medium.com/@charpeni/…。
  • 感谢您的链接。第二个版本几乎等同于第一个版本的编译版本,只是如该博客文章中所示,函数的主体被移动到构造函数中。我对基准中的“箭头函数”与“绑定函数”感到困惑,因为博客文章的顶部显示带有箭头函数的类属性被编译为绑定函数。你知道博文中使用了什么代码吗?
  • 我同样困惑为什么自动绑定装饰器会成为“救世主”?它在实例上调用.bind,就像编译的箭头函数一样。我错过了什么? github.com/andreypopp/autobind-decorator/blob/…
【解决方案2】:

我写了一个小组件来绑定其他组件的所有方法。喜欢的可以试试:http://www.marouen-mhiri.com/react/autobinding-es6-classes-in-react-another-approach/

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多