【问题标题】:Should I be binding also inbuilt React methods?我应该绑定内置的 React 方法吗?
【发布时间】:2019-10-19 21:45:35
【问题描述】:

React.Component 类中使用bind用户创建的方法是一种常见的做法。

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() strong>,大​​部分代码 sn-ps 以及官方文档似乎没有明确地 bindthis

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

【问题讨论】:

  • 你自己什么时候会打电话给componentDidMount?绑定其他函数的原因是当您将函数作为回调传递时,如果您没有绑定它,它将变为未绑定,但如果您从未将 this.componentDidMount 作为回调传递,则无需担心
  • 如果你想测试一下,我建议你制作一个带有按钮的组件,并将onClick设置为this.componentDidMount,看看会发生什么。然后你会自己发现它是否绑定。 <button onClick={this.componentDidMount}/>
  • @TKoL 诚然,是的,我没有想到它背后的大局是我们很少会真正回调“生命周期方法”。虽然从理论上讲,它仍然是一个关于为什么或是否绑定的有效问题(正如您在评论中指出的那样,现在我自己检查一下)
  • 生命周期方法来自父类,即React.Component。因为它们已经绑定在父级中,而你只是覆盖它们,你不需要再次绑定它们
  • Afaik 这些方法是绑定的,因为 React 库不使用 ES6 类。示例代码:jsfiddle.net/khrismuc/fnjs468g

标签: javascript reactjs methods binding extension-methods


【解决方案1】:

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

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

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

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

而且你不需要绑定生命周期方法

编辑:正如https://reactjs.org/docs/handling-events.html 中的文档所述

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

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

【讨论】:

  • And you don't need to bind the life-cycle methods OP 的问题是为什么,这并没有回答。
【解决方案2】:

我制作了一个包含以下内容的组件:

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

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

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

--编辑

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

【讨论】:

    猜你喜欢
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多