如何删除警告“无法对未安装的组件执行反应状态更新"; [英] how to remove the warning "can't perform a react state update on unMounted Component"

查看:49
本文介绍了如何删除警告“无法对未安装的组件执行反应状态更新";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个身份验证系统,在该系统中,用户可以登录,如果经过身份验证,则将用户重定向到主页...它工作正常,但是唯一的问题是,它警告我无法更新未安装组件的状态我已经在互联网上尝试了与该问题相关的所有方法,但未能删除警告...

I have an authentication system in which the user logins and if authenticated then redirect user to home page... it is working fine but the only problem is that it is giving me a warning of can't update state on unmounted component I have tried all the approaches related to this problem on internet but failed to remove warning...

我已经设置了isMounted标志,并在componentDidMount中将其设置为true,但是并没有帮助..我也尝试在componentWillUnMount中清除Interval和Timeout,但仍然失败...

I have set a flag of isMounted and set it to true in componentDidMount but didn't help.. I also tried to clearInterval and Timeout in componentWillUnMount but still failed...

login = () => {
  var mythis = this;
  var name = this.state.name;
  var  password = this.state.password
    this.setState({isLoading:true,show:true});
  this.interval = setInterval(function(){
    mythis.setState({show:true})
  },300);
  $.ajax({
    url : 'http://localhost:4000/login',
    type : "POST",
    data : {username:name,password:password},
    success : function(data){
    mythis.firstTimeout =  setTimeout(function(){
        clearInterval(mythis.interval);
      if(data == true){


    mythis.setState({show:false});
   mythis.secondTimeout=setTimeout(function(){

      mythis.setState({isLoading:false});

    },200)

      }
      else {

        mythis.setState({show:false});
        mythis.secondTimeout=setTimeout(function(){
          mythis.setState({isLoading:false})
        },200)
      }

    },2000)

    }.bind(this)
  })
}

componentWillUnMount(){
//this._isMounted = false;
clearInterval(this.interval);
clearTimeout(this.firstTimeout);
clearTimeout(this.secondTimeout);

}

render(){
return (
<div>
{this.state.isLoading ? (
        <div>
           <Loading
             show={this.state.show}
             color="red"
             showSpinner={false}
           />
           </div>
      ):''}
}
</div>
)

推荐答案

如果您正在构建此React应用,则可以在componentDidMount生命周期方法中调用ajax请求. 首先设置您的私人变量 _isMounted=false

if this a react app you are building, you call ajax request in componentDidMount lifecycle method. first set your private var _isMounted=false

然后在componentDidMount中:

Then in componentDidMount:

componentDidMount() {
    this._isMounted = true;
    .... your ajax request here
}

在您的Ajax成功功能中:

in your ajax success function:

if (this._isMounted) {
    this.setState({ isLoading: false });
   }

然后在componentWillUnmount生命周期方法中:

then in componentWillUnmount lifecycle method:

componentWillUnmount(){
  this._isMounted= false
}

这篇关于如何删除警告“无法对未安装的组件执行反应状态更新";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆