我收到此错误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生命周期函数来设置超时,而不是将其称为image的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>