以下哪项是关于 React 类组件性能的最佳实践:
在构造函数中绑定(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' */ }
使用箭头函数代替普通函数:
constructor(props) { /* some code */ } render() { return( <div> <input onChange={this.onChange} </div> ); } onChange = (event) => { /* some code involving 'this' */ }
坚持使用普通函数,但在 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/