我正在阅读 Reactjs 和
componentDidMount: function() {
this.serverRequest = $.get(this.props.source, function (result) {
var lastGist = result[0];
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}.bind(this));
}
根据我的理解,将 this if 绑定(bind)到 this.setState
以便在外部调用时,this
将引用正确的对象。但为什么我们不需要它来实现 this.props.source
呢?
最佳答案
因为 this.props.source
是传递给 $.get
的参数 - 它在 componentDidMount
内执行时仍然具有正确的上下文> 方法。只有在 $.get
方法的回调中,上下文才会丢失,该上下文是从 jQuery 库中的某个位置执行的。
保留上下文的另一种方法是使用 arrow function (这是 es6,所以你现在需要一个转译器),它将为你进行绑定(bind):
$.get(this.props.source, (result) => {
// ...
});
关于javascript - ReactJS 中的 Bind(this) 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35947377/