[英]React warning setState(…): Can only update a mounted or mounting component
I get this Error/Warning in my console: 我在控制台中收到此错误/警告:
setState(...): Can only update a mounted or mounting component.
setState(...):只能更新已安装或正在安装的组件。
Here's where I mount the component: 这是我安装组件的位置:
componentDidMount()
{
if (this.isVisible()) {
this.setState({visible: true});
}
this.bindEventListeners();
}
This is the code that is causing the issue: 这是导致问题的代码:
bindEventListeners()
{
let visibilityEvent = function (event) {
event.currentTarget.removeEventListener(event.type, visibilityEvent);
// protect the component against unloading
if (this.isVisible()) {
this.setState({visible: true});
}
// no need to call the timeout when its already visible
if (!this.state.visible) {
let scrollEvnt = setTimeout(function () {
EventContainer.readWindowEvent('scroll', visibilityEvent);
}, 100);
this.setState({scrollEv: scrollEvnt});
}
}.bind(this);
EventContainer.readWindowEvent('scroll', visibilityEvent);
}
This line to be more precise: 这行更精确:
this.setState({scrollEv: scrollEvnt});
this.setState({scrollEv:scrollEvnt});
If I understand it correctly it means that I need a way to unmount the scroll event. 如果我正确理解它,则意味着我需要一种卸载滚动事件的方法。 But I am not sure if this is even possible.
但是我不确定这是否可能。 I am pretty sure you can't unbind a scroll event in (vanilla)javascript/React.
我很确定您无法取消(香草)javascript / React中的滚动事件。
isVisible()
{
let isVisible = true;
try {
let heightElement = ReactDOM.findDOMNode(this).getBoundingClientRect().top;
isVisible = heightElement - window.innerHeight < 0;
} catch (error) {
console.warn('Falling back');
}
return isVisible;
}
I might be wrong but I am not sure how to resolve this warning/error. 我可能是错的,但是我不确定如何解决此警告/错误。 Maybe someone can help me out?
也许有人可以帮助我? Any help is appreciated :)
任何帮助表示赞赏:)
Many thanks in advance! 提前谢谢了!
I think we might need to see more of the code to figure this one out. 我认为我们可能需要查看更多代码才能解决这一问题。
A couple of questions: 几个问题:
This diagram has helped me a lot in keeping track of where everything happens in a react object's lifecycle 该图对跟踪对象的生命周期中发生的所有事情有很大帮助
You need to remove the scroll event listener in componentWillUnmount
您需要在
componentWillUnmount
删除滚动事件侦听器
Something along the lines of the following should work: 符合以下要求的方法应该起作用:
constructor(props) {
super(props);
this.onScroll = this.onScroll.bind(this);
}
componentDidMount()
{
window.addEventListener('scroll', this.onScroll);
}
componentWillUnmount()
{
window.removeEventListener('scroll', this.onScroll);
}
onScroll(event)
{
//handle event here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.