我收到此錯誤setState(...): Can only update a mounted or mounting component.
,但我無法弄清楚如何解決該問題。React JS setState(...):只能更新已安裝或正在安裝的組件
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>
移動你的計時器函數到'componentDidMount'。你從'渲染器'裏面調用它並不能很好地傳達你的意圖。有關生命週期函數的更多信息,請參見:https://facebook.github.io/react/docs/react-component.html – Kyle
@Kyle仍然會這樣做,如果我從那裏執行它 –