我还应该绑定内置的 React 方法吗?

Should I be binding also inbuilt React methods?

通常的做法是 bind React.Component class.

中的用户创建方法
class App extends React.Component { // simplified example, not actual code
   constructor(){ 
      //...
      this.logIn=this.logIn.bind(this) // Binding of a method
   }
}

当然,这是因为我们需要显式 bind 方法到“this class”,否则我们将用 this 引用 window 对象!


但我不清楚的是,至少从我查看的文档等来看,如果我们使用内置的生命周期方法,例如 render()componentDidMount(),大多数代码片段和官方文档似乎 没有明确地 bindthis

class App extends React.Component {
   constructor(){
      //....
      this.componentDidMount = this.componentDidMount.bind(this) 
      // is there reason why we don't do this ^ ??
   }
}

Naturally, this is beceause we need to explicitly bind the method to "this class", otherwise we would be referencing with this the window object!

你也可以使用箭头函数来使用它而无需绑定:

sayHello=()=>{
  return 'hello';
}

myOtherFunction=()=>{
  console.log('I can acces the other function! Say:'+ this.sayHello())
}

而且您不需要绑定 life-cycle 方法

编辑:正如 https://reactjs.org/docs/handling-events.html

中的文档所述

You have to be careful about the meaning of this in JSX callbacks. In JavaScript, class methods are not bound by default. If you forget to bind this.handleClick and pass it to onClick, this will be undefined when the function is actually called.

所以假设生命周期方法是默认绑定的。

我用以下内容制作了一个组件:

...
componentDidMount() {
    var that = this;
    var x = 0;
}
...
render() {
    ....
    <button onClick={this.componentDidMount}>DID MOUNT</button>
    ....
}

结果是 -- 当函数最初挂载时,that 是正确绑定的,但是当从按钮上单击时,它不是。

这意味着 componentDidMount 尚未绑定,但是 它是从 React 内部使用适当的上下文调用的,因此不需要绑定。

-- 编辑

也许还值得注意:如果您使用自动绑定包,如果它绑定了生命周期方法,则值得检查。 autobind-decorator 事实上!