javascript - 只能更新已安装或正在安装的组件

标签 javascript

我收到以下警告

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the undefined component.

这是我的代码

var React = require('react');
import DetectUtil from 'pofod/detectUtil';
function withSubscription(WrappedComponent,MobileComponent) {
    class Subscription extends React.Component{
        constructor(props){
            super(props);
            this.state={
                ExternalComponent:innerWidth>1023?WrappedComponent:MobileComponent
            }
            this.getPageLangParams=this.getPageLangParams.bind(this);
            this.MonitorSize = this.MonitorSize.bind(this);
        }
        getPageLangParams () {
            var query=this.props.location?(this.props.location.query?this.props.location.query:{}):{};
            var lang=this.props.lang||query.lang||DetectUtil.languageFamily()||'zh';
            return lang;
        }
        MonitorSize(){
            this.setState({
                ExternalComponent:innerWidth>1023?WrappedComponent:MobileComponent
            })
        }
        componentDidMount(){
            window.addEventListener('resize',this.MonitorSize)
        }
        componentWillMount(){
            window.removeEventListener('resize',this.MonitorSize)
        }
        render(){
            let lang = this.getPageLangParams();
            let ExternalComponent = this.state.ExternalComponent;
            return (
                <ExternalComponent lang={lang}/>
            )
        }
    }
    return Subscription;
}

module.exports = withSubscription;

最佳答案

您混淆了 componentWillMount 和 componentWillUnmount。

EventListener 正在 componentWillMount 上移除,但您应该在卸载之前移除它,例如componentWillUnmount.

因此,当卸载组件时,MonitorSize 停止触发。 它应该是这样的:

componentWillUnmount(){
     window.removeEventListener('resize',this.MonitorSize)
}

关于javascript - 只能更新已安装或正在安装的组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43651364/

相关文章:

JavaScript - 数组通过引用传递但在重新分配时丢失

javascript - 如何删除javascript中的最后一行?

javascript - 如果渲染任何其他 View ,则 Backbone View 重新渲染

javascript - 调用 JavaScript/jQuery 函数的不同方法的性能

javascript - 如何使用 python Flask 应用程序在 d3js 图表中动态加载 json 数据

javascript - 如何在网页 View Android 中的网页上运行 javascript

javascript - 如何使用 Javascript 在 Firefox 中获取 Windows(已登录)用户名

javascript - 如何使 iframe 的高度始终延伸到浏览器窗口的底部?

javascript - 我可以一键设置状态并调用函数吗?

javascript - 加载异步属性的脚本会延迟 onload 事件吗?