React应用程序中的setInterval [英] setInterval in a React app
问题描述
我在React仍然相当新,但我一直在慢慢地磨,我遇到了一些我坚持不懈的事情。
I'm still fairly new at React, but I've been grinding along slowly and I've encountered something I'm stuck on.
我正在尝试在React中构建一个计时器组件,说实话我不知道我是否正确(或有效)。在我的下面的代码中,我将状态设置为返回一个对象 {currentCount:10}
并且一直在玩弄 componentDidMount
, componentWillUnmount
,渲染
,我只能将状态从10倒数到9。
I am trying to build a "timer" component in React, and to be honest I don't know if I'm doing this right (or efficiently). In my code below, I set the state to return an object { currentCount: 10 }
and have been toying with componentDidMount
, componentWillUnmount
, and render
and I can only get the state to "count down" from 10 to 9.
两部分问题:我出错了什么?并且,是否有更有效的方法来使用setTimeout(而不是使用 componentDidMount
& componentWillUnmount
)?
Two-part question: What am I getting wrong? And, is there a more efficient way of going about using setTimeout (rather than using componentDidMount
& componentWillUnmount
)?
提前谢谢。
import React from 'react';
var Clock = React.createClass({
getInitialState: function() {
return { currentCount: 10 };
},
componentDidMount: function() {
this.countdown = setInterval(this.timer, 1000);
},
componentWillUnmount: function() {
clearInterval(this.countdown);
},
timer: function() {
this.setState({ currentCount: 10 });
},
render: function() {
var displayCount = this.state.currentCount--;
return (
<section>
{displayCount}
</section>
);
}
});
module.exports = Clock;
推荐答案
我看到你的代码有4个问题:
I see 4 issues with your code:
- 在您的计时器方法中,您始终将当前计数设置为10
- 您尝试更新状态渲染方法
- 您不使用
setState
方法来实际更改状态 - 您是不存储您的intervalId状态
- In your timer method you are always setting your current count to 10
- You try to update the state in render method
- You do not use
setState
method to actually change the state - You are not storing your intervalId in the state
让我们尝试解决这个问题:
Let's try to fix that:
componentDidMount: function() {
var intervalId = setInterval(this.timer, 1000);
// store intervalId in the state so it can be accessed later:
this.setState({intervalId: intervalId});
},
componentWillUnmount: function() {
// use intervalId from the state to clear the interval
clearInterval(this.state.intervalId);
},
timer: function() {
// setState method is used to update the state
this.setState({ currentCount: this.state.currentCount -1 });
},
render: function() {
// You do not need to decrease the value here
return (
<section>
{this.state.currentCount}
</section>
);
}
这将导致计时器从10减少到-N。如果你想让计时器减少到0,你可以使用稍微修改过的版本:
This would result in a timer that decreases from 10 to -N. If you want timer that decreases to 0, you can use slightly modified version:
timer: function() {
var newCount = this.state.currentCount - 1;
if(newCount >= 0) {
this.setState({ currentCount: newCount });
} else {
clearInterval(this.state.intervalId);
}
},
这篇关于React应用程序中的setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!