Reactjs 如何在react中发生卸载组件错误时导航到另一页而不使用setState()
我正在学习编写一个倒数计时类的应用程序,一切正常,但我有一个问题,每当我试图导航到另一个页面而不按暂停,我会得到错误“只能更新装载或装载组件,这通常意味着你调用了卸载组件上的setState”。这意味着什么,我如何修复它?事先非常感谢Reactjs 如何在react中发生卸载组件错误时导航到另一页而不使用setState(),reactjs,components,unmount,Reactjs,Components,Unmount,我正在学习编写一个倒数计时类的应用程序,一切正常,但我有一个问题,每当我试图导航到另一个页面而不按暂停,我会得到错误“只能更新装载或装载组件,这通常意味着你调用了卸载组件上的setState”。这意味着什么,我如何修复它?事先非常感谢 import React from 'react'; import SubjectForm from './SubjectForm'; import {connect} from 'react-redux'; import {editSubject, remove
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);
很抱歉代码太长。导航到另一个页面卸载组件,但setInterval中的函数仍在运行,并试图更新卸载的组件状态。根据应用程序所需的行为,您有2个选项: 1-使用redux存储计时器并分派启动/暂停/停止操作 如果您导航,它将继续运行
2-组件中的clearInterval将卸载组件重置或停止计时器的方法如果您导航谢谢,我将尝试两种方法,希望我能在接下来的几天内学会如何执行,至少我现在有了一个方向