我有一个身份验证系统,用户登录后,如果通过身份验证,则将用户重定向到主页...它工作正常,但唯一的问题是它向我发出无法更新已卸载组件状态的警告我已经尝试了互联网上与此问题相关的所有方法,但未能删除警告...
我已经设置了 isMounted 标志并在 componentDidMount 中将其设置为 true 但没有帮助..我还尝试在 componentWillUnMount 中清除Interval和Timeout但仍然失败...
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请求。
首先设置你的私有(private)变量
_isMounted=false
然后在componentDidMount中:
componentDidMount() {
this._isMounted = true;
.... your ajax request here
}
在你的ajax成功函数中:
if (this._isMounted) {
this.setState({ isLoading: false });
}
然后在 componentWillUnmount 生命周期方法中:
componentWillUnmount(){
this._isMounted= false
}
关于jquery - 如何删除警告 "can' t 对未安装的组件执行 react 状态更新”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53991044/