问题描述
我对 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
和 render
并且我只能让状态从 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
让我们尝试解决这个问题:
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!