【问题标题】:Why is "this" bound different in some instances, but the same in others in React?为什么在某些情况下“this”绑定不同,但在 React 中的其他情况下却相同?
【发布时间】:2018-05-17 23:30:58
【问题描述】:

在这个组件中,如果它不是箭头函数,我无法通过 this.functionName 调用 render 方法中的函数。但是,我可以在箭头函数和常规函数中有效地调用 this.setState。为什么像这样的 React 组件中的“this”在某些情况下是不同的,但在其他情况下却是一样的?

import React from 'react';

class Address extends React.Component {

state = {
    fullAddress: "5001"
}

componentDidMount() {
    this.setState({
        fullAddress: "hello"
    })
}

hello = () => {
    this.setState({
        fullAddress: "hello1"
    })
}

logMessage() {
    console.log(this.state.fullAddress);
}

 render() {
   return (
     <div className="address">
       {this.state.fullAddress}
       <input type="button" value="Log" onClick={this.hello} />
     </div>
   );
 }
}

export default Address;

【问题讨论】:

标签: javascript reactjs ecmascript-6 this


【解决方案1】:

在您的示例中,logMessage 可能会中断,因为您需要为其指定 this 上下文。

在这种情况下,只需将bind 放在Address 的构造函数中,如下所示:

class Address extends Component {
  constructor(props) {
    super(props)

    this.logMessage = this.logMessage.bind(this)
  }
} 

第二种方法与您已经使用 hello 的箭头函数相同。 Arrow functions 保留您当前的上下文 (this),这就是为什么您可以在 hello 的正文中访问 this.setState

【讨论】:

  • 谢谢。不过我很困惑,为什么我可以在箭头函数和常规函数中调用 this.setState 并让它在两种情况下都有效?不应该在这些函数中绑定不同的“this”,以使 this.setState 在其中一个中不起作用?
  • 箭头函数会自动为您保留this(这就是this.setState 起作用的原因)。如果您不使用箭头函数,例如在logMessage 中,您需要指定谁是this(在构造函数中),否则this.setState 将不起作用。
  • 不,这不准确。我可以在上面的componentDidMount中调用this.setState,这是一个常规函数,它工作正常。
  • 它适用于componentDidMount,因为您的课程扩展 React.Component。这是您的基类负责的生命周期方法。而logMessage 是一个新事件,您需要指定它应该调用哪个this
  • @Dog 如果您对此有任何其他问题,请随时再次提问:)
猜你喜欢
  • 2019-02-25
  • 2010-10-12
  • 1970-01-01
  • 2014-06-13
  • 2015-12-24
  • 2019-12-27
  • 1970-01-01
  • 2020-08-25
  • 1970-01-01
相关资源
最近更新 更多