zoukankan      html  css  js  c++  java
  • 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.的解决方案

    一,出现以上异常的原因分析:

      因为在组件挂载(mounted)之后进行了异步操作,比如ajax请求或者设置了定时器等,而你在callback中进行了setState操作。当你切换路由时,组件已经被卸载(unmounted)了,此时异步操作中callback还在执行,因此setState没有得到值。

    二,解决方案:

    (1)在卸载的时候对所有的操作进行清除:

    componentDidMount = () => { //1.ajax请求 $.ajax('你的请求',{}) .then(res => { this.setState({ aa:true }) }) .catch(err => {}) //2.定时器 timer = setTimeout(() => { //dosomething },1000) } componentWillUnMount = () => { //1.ajax请求 $.ajax.abort() //2.定时器 clearTimeout(timer) }
    (2)、设置一个flag,当unmount的时候重置这个flag
    componentDidMount = () => {
        this._isMounted = true;
        $.ajax('你的请求',{})
            .then(res => {
                if(this._isMounted){
                    this.setState({
                        aa:true
                    })
                }
            })
            .catch(err => {})
    }
    componentWillUnMount = () => {
        this._isMounted = false;
    }

    (3)、组件卸载的时候直接return
    componentDidMount = () => {
        $.ajax('你的请求',{})
        .then(res => {
            this.setState({
                data: datas,
            });
        })
        .catch(error => {
    
         });
    }
    componentWillUnmount = () => {
        this.setState = (state,callback)=>{
          return;
        };
    }
  • 相关阅读:
    Form 中调用指定请求并给定默认参数
    OAF 汇总行的做法
    EBS 开发常用SQL
    EBS 中常用的配置文件及说明
    OAF 常见概念介绍
    OAF 多语言的实现
    OAF 个性化基础
    OAF 开发前置配置
    条款20 STL函数对象
    条款19 command 模式与好莱坞法则
  • 原文地址:https://www.cnblogs.com/pyj63/p/9492596.html
Copyright © 2011-2022 走看看