[英]React JS setState(…): Can only update a mounted or mounting component
我收到此错误setState(...): Can only update a mounted or mounting component.
但我无法解决该问题。
import React, { Component } from 'react';
import Loading1 from '../images/loading1.gif';
class LoadingSpinner extends Component {
constructor(props){
super(props);
this.changeState = this.changeState.bind(this);
this.timer = this.timer.bind(this);
}
state = {
loadingImg: Loading1,
loading: true
}
timer(){
var self = this;
var startTime = new Date().getTime();
var interval = setInterval(function () {
if (new Date().getTime() - startTime > 3000) {
clearInterval(interval);
return;
}
self.changeState();
}, 2000);
}
changeState(){
this.setState({
loading: false,
})
}
render() {
const topMargin = {
marginTop: "50px"
}
return (
<div className="containter" style={topMargin}>
<center>
{this.state.loading ? <img src={this.state.loadingImg} onLoad= {this.timer()} alt="Loading..." /> : <h2>Unable To Find What You Are Looking For!</h2> }
</center>
</div>
);
}
}
export default LoadingSpinner;
这是导致问题的我的代码。
基本上,我想要这样,以便在设置的时间后它将从loading1.gif更改为“无法找到您要查找的内容”。 它会执行此操作,但是会引发错误setState(...): Can only update a mounted or mounting component.
这是我无法摆脱的。
这就是我所说的加载微调框
<Tab label="Applicant Details" value="GetCasePersonal">
{this.state.GetCasePersonal.length === 0 ? <LoadingSpinner /> :
<div>
<ViewPersonalDetails Case={this.state.GetCasePersonal} />
</div>
}
</Tab>
您不需要使用setInterval
函数,可以轻松地使用setTimeout
进行操作,并且应该使用React生命周期函数来设置超时,而不是将其调用为onLoad。
class LoadingSpinner extends React.Component { constructor(props){ super(props); this.timeout = null; this.changeState = this.changeState.bind(this); } state = { loadingImg: '', loading: true } componentDidMount(){ this.timeout = setTimeout( () => { console.log('I am changing state'); this.changeState(); }, 3000); } componentWillUnmount() { clearTimeout(this.timeout); } changeState(){ this.setState({ loading: false, }) } render() { const topMargin = { marginTop: "50px" } return ( <div className="containter" style={topMargin}> <center> {this.state.loading ? <img src={this.state.loadingImg} alt="Loading..." /> : <h2>Unable To Find What You Are Looking For!</h2> } </center> </div> ); } } ReactDOM.render(<LoadingSpinner/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div>
这里有关于此的很好的文档https://facebook.github.io/react/blog/2015/12/16/ismount-antipattern.html
处理此类问题时,一个好的做法是搜索react facebook文档。
private _isMount = false;
componentDidMount() {
this._isMount = true;
}
componentWillUnmount()
{
this._isMount = false;
}
timerJob()
{
if(this._isMount == false)
return;
// setState
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.