gpt4 book ai didi

javascript - React JS setState(...) : Can only update a mounted or mounting component

转载 作者:行者123 更新时间:2023-11-28 17:52:22 27 4
gpt4 key购买 nike

我收到此错误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 Components. 我无法摆脱该错误。

这就是我调用加载微调器的方式

<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>

关于javascript - React JS setState(...) : Can only update a mounted or mounting component,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45217620/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com