componentDidMount: function() {
$.get(this.props.source, function(result) {
var lastGist = result[0];
if (this.isMounted()) {
this.setState({
username: lastGist.owner.login,
lastGistUrl: lastGist.html_url
});
}
}.bind(this));
}
这是react中的一段代码,我不太懂.bind(this))是指哪个this,谢谢!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
当前react的实例
看
this写在哪个function上的, 明显是componentDidMount这个function上的,那其指向的就是componentDidMount这个function的主人,react的话就是react实例了。ps: 如果再扩展一下,这个componentDidMount也被人为的bind到其他地方去了,那就指向就看被bind给谁了。不过,一般没人那么用,其他js可能有这种写法
this指的是当前组件的域,就是$.get()这个方法所在的域。这个域中存在这props和state。然而回调的时候,function中又产生一个新的域(this),新的域中没有props和state。 .bind方法就是把外层的this传到了function中,这样function中的this下也有props和state。这时候你调用this.setState和this.isMounted方法才合法,否则调不到。也可以在外部声明
var self = this; 然后用self.setState。