【发布时间】:2019-08-28 16:27:50
【问题描述】:
我有一个表格可以呈现映射的patientInfo array。当patient.status 不为空/有值时,倒计时计时器开始为阵列中的个别患者倒计时。这发生在componentDidMount()。现在我想在componentWillUnMount() 上清除Interval,但倒计时并没有停止。
基本上我只需要在时间到 0 时清除倒计时。假设计时器从 60 秒到 0 时开始倒计时,清除间隔。没有停止按钮或类似的东西可以执行。当时间达到 0 秒时,我需要它自动清除间隔。当个体患者具有状态价值时,倒计时时间开始。希望这是有道理的
PatientInfo Array
patientInfo = [
{ count: 959999, room: "1", name: 'John Nero', status: ''},
{ count: 959999, room: "2", name: 'Shawn Michael', status: ''},
{ count: 959999, room: "3", name: 'Gereth Macneil', status: ''}
]
//starts countdown when the patient.status has value which comes from user input
componentDidMount() {
this.countDownInterval = setInterval(() => {
this.setState(prevState => ({
patientInfo: prevState.patientInfo.map((patient) => {
if (patient.status !== '') {
// subtract a sec
return { ...patient, count: patient.count - 1000};
}
return patient;
})
}));
}, 1000);
}
//when the patient.count is 950999 clearInterval doesn't work
//edited after some comments but still doesn't work
componentWillUnmount() {
this.state.patientInfo.map((patient) => {
if (patient.count <= 950999) {
clearInterval(this.countDownInterval);
}
});
}
//after a few try the following seems to work but not sure if this is the correct way
componentDidMount() {
this.countDownInterval = setInterval(() => {
this.setState(prevState => ({
patientInfo: prevState.patientInfo.map((patient) => {
if (patient.status !== '') {
if (patient.count <= 950999) {
clearInterval(this.countDownInterval);
}
return { ...patient, count: patient.count - 1000 };
}
return patient;
})
}));
}, 1000);
}
【问题讨论】:
-
[提示] 您可以简单地使用
setInterval而不是window.setInterval -
为什么要在 setState 中删除它。为什么不只是
componentWillUnmount() { clearInterval(this.countDownInterval); -
您对
clearInterval的条件过于具体。为了让您清除间隔,您的组件必须安装 95 秒和 0.999 毫秒。我很确定 JS 甚至无法确保该级别的准确性。你的意思是patient.count >== 950999? -
我认为在
componentWillUnmount内部使用setState的想法没有任何效果。 -
嗨 Jereme,请阅读此内容 - stackoverflow.com/help/someone-answers,然后尝试关闭问题。
标签: javascript reactjs setinterval clearinterval