我正在通过编写类似应用程序的倒计时来学习 React,一切正常,但我遇到了问题,每当我尝试导航到另一个页面而不按暂停时,我都会收到错误“只能更新挂载或挂载组件,这通常意味着你在卸载组件上调用 setState()。这是什么意思,我该如何解决?非常感谢你。
import React from 'react';
import SubjectForm from './SubjectForm';
import {connect} from 'react-redux';
import {editSubject, removeSubject} from '../actions/subjectAction';
class StartPage extends React.Component{
constructor(props){
super(props);
this.state={count:this.props.subject.hour*60*60+this.props.subject.minute*60,
name:'run',
alert:''
};
this.timer = null;
this.stateChange=this.state.count
this.originTime = this.props.subject.hour*60*60+this.props.subject.minute*60;
}
setStateCountdown=(num)=>{
this.setState({count:num})
}
setStateAlert=(text)=>{
this.setState({alert:text})
}
setStateButtonChange=(text)=>{
this.setState({name:text})
}
begin=()=>{
clearInterval(this.timer)
this.timer=setInterval(()=>{
this.stateChange--
this.setStateCountdown(this.stateChange)
let timeLeft=this.stateChange
if(this.stateChange<0){
this.setStateAlert('done');
clearInterval(this.timer);
return;
}
let hourleft = Math.floor(timeLeft / (60 * 60));
let minuteleft = Math.floor((timeLeft % (60 * 60)) / 60);
let secondleft = timeLeft % 60;
this.setStateAlert(`you have ${hourleft} hour ${minuteleft} minute and ${secondleft} second until reaching your goal`);
},1000);
}
pause=()=>{
clearInterval(this.timer)
console.log(this.state.count)
if(this.state.count<this.originTime){
this.setStateButtonChange('resume')
}
}
reset=()=>{
const pressConfirm = confirm('are you sure you want to reset?')
if(pressConfirm===true){
console.log(this.state.count)
clearInterval(this.timer)
this.stateChange=this.originTime;
this.callbackFuncCountdown(this.stateChange)
this.callbackFunctionButtonChange('run')
this.callbackFunctionAlert('lets begin your study again')
}
}
render(){
return(
<div>
<SubjectForm subject={this.props.subject}/>
<button onClick = {this.begin}>{this.state.name}</button>
<button onClick = {this.pause}>pause</button>
<button onClick = {this.reset}>reset</button>
<h3>{this.state.alert}</h3>
</div>
);
}
};
const mapStateToProps = (state,props)=>{
return{
subject: state.subjects.find((subject)=>subject.id===props.match.params.id)
};
}
export default connect(mapStateToProps)(StartPage);
我很抱歉长代码。