Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

demo 11 里面的 this.isMounted 的作用是什么? #43

Closed
yuxino opened this issue Jan 6, 2018 · 7 comments
Closed

demo 11 里面的 this.isMounted 的作用是什么? #43

yuxino opened this issue Jan 6, 2018 · 7 comments

Comments

@yuxino
Copy link

yuxino commented Jan 6, 2018

阮老师你好。我想请教下这一段里面的this.isMounted的作用。

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));
},

看README的描述

did methods which are called right after something happens.

componentDidMount这个钩子调用的时候 this.isMounted应该总是为true吧。那么这个判断是不是多余的。

@ruanyf
Copy link
Owner

ruanyf commented Jan 6, 2018

谢谢指出,这个判断确实是多余的。我把它删掉。

@ruanyf ruanyf closed this as completed Jan 6, 2018
@vipcxj
Copy link

vipcxj commented Jan 6, 2018

并不一定吧~ isMounted是在回调函数中,并且涉及网络请求,没人能保证它执行的时候仍旧是Mounted的

@yuxino
Copy link
Author

yuxino commented Jan 6, 2018

@vipcxj componentDidMount是在isMounted状态为true的时候执行的回调函数,所以是可以保证的。我刚才仔细看了一下README的实例是正确的,有误的只是demo11文件夹里面的那个实例代码。而且这个东西不好

@vipcxj
Copy link

vipcxj commented Jan 7, 2018

@Nbsaw 没记错的话,应该是执行get网络请求后才调用的回调函数,如果网比较差,这就会有一个时间差了啊,如果期间被unmount了,也是可能的

@ruanyf
Copy link
Owner

ruanyf commented Jan 8, 2018

理论上,获取到数据的时候,组件是可能被卸载的。但是,这个例子里,确实是多余的判断。

另外,isMounted这个 API 也已经被废掉了,所以还是去掉比较好。facebook/react#5465

@vipcxj
Copy link

vipcxj commented Jan 8, 2018

@ruanyf 我把整个issure都看了下,基本就是react的开发者嫌isMounted不够优雅,想废除它,但又没在react内部给一个完美的代替方案,所以另一个react的贡献者就不同意了。然后就是提出各种workaround,然而所有workaround都不是react自带的,全部仅仅是workaround~ 没看到这个issure的岂不是要被坑?

@ruanyf
Copy link
Owner

ruanyf commented Jan 8, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants