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

时间:2019-06-04 11:03:01

标签: javascript reactjs methods binding extension-methods

通常的做法是在bind类中使用 React.Component 用户创建的方法。

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() {{1 }} ,大​​多数代码段以及官方文档似乎没有bindthis

class App extends React.Component {
   constructor(){
      //....
      this.componentDidMount = this.componentDidMount.bind(this) 
      // is there reason why we don't do this ^ ??
   }
}
  • 我们扩展的React.Component内是否已经有一些内置绑定?
  • 或者为什么我们不需要像我们创建的其余方法({{1一样)那样显式bind生命周期方法componentDidMount() }})

2 个答案:

答案 0 :(得分:1)

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

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

结果在-最初安装该函数时,that已正确绑定,但是从按钮单击时却没有绑定。

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

-编辑

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

答案 1 :(得分:-2)

  

自然,这是因为我们需要将方法显式绑定到“此类”,否则我们将以此窗口对象进行引用!

您还可以使用箭头功能而无需绑定即可使用此功能:

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

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

您不需要绑定生命周期方法

编辑:如文档在https://reactjs.org/docs/handling-events.html

中所述
  

您必须小心JSX回调中的含义。在JavaScript中,默认情况下不绑定类方法。如果忘记绑定this.handleClick并将其传递给onClick,则在实际调用该函数时将无法定义。

因此,默认情况下,生命周期方法是绑定的。

相关问题