admin管理员组文章数量:1299991
I'm a bit confused, what is the difference between this sintax:
constructor(props) {
super(props);
this.state = {
openPane: false
}
this.togglePaneHelper = this.togglePaneHelper.bind(this);
}
ponentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper);
}
ponentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
and this one:
constructor(props) {
super(props);
this.state = {
openPane: false
}
}
ponentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper.bind(this));
}
ponentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
My concern is that the second syntax isn't removing correctly the listner and it cause this warning:
Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. This is a no-op. Please check the code for the undefined ponent.
I'm a bit confused, what is the difference between this sintax:
constructor(props) {
super(props);
this.state = {
openPane: false
}
this.togglePaneHelper = this.togglePaneHelper.bind(this);
}
ponentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper);
}
ponentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
and this one:
constructor(props) {
super(props);
this.state = {
openPane: false
}
}
ponentDidMount() {
document.body.addEventListener('click', this.togglePaneHelper.bind(this));
}
ponentWillUnmount() {
document.body.removeEventListener('click', this.togglePaneHelper);
}
My concern is that the second syntax isn't removing correctly the listner and it cause this warning:
Warning: setState(...): Can only update a mounted or mounting ponent. This usually means you called setState() on an unmounted ponent. This is a no-op. Please check the code for the undefined ponent.
Share
Improve this question
edited Feb 5, 2016 at 13:29
daniele bertella
asked Feb 5, 2016 at 12:10
daniele bertelladaniele bertella
7251 gold badge7 silver badges14 bronze badges
1 Answer
Reset to default 11IMPORTANT:
a.bind(this) !== a.bind(this)
According to MDN:
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
Your first approach overrides this.togglePaneHelper
with new, bound function. Second one removes different event listener function than it was added - both addEventListener
and removeEventListener
have to get the same reference of function.
本文标签:
版权声明:本文标题:javascript - React how to remove listners correctly in componentWillUnmount, why do I need the bind in the constructor? - Stack 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741656096a2390768.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论