【发布时间】:2016-07-17 21:16:35
【问题描述】:
我对 React 还很陌生,但我一直在慢慢磨练,遇到了一些我一直坚持的问题。
我正在尝试在 React 中构建一个“计时器”组件,老实说,我不知道我这样做是否正确(或有效)。在下面的代码中,我将状态设置为返回一个对象{ currentCount: 10 },并且一直在玩弄componentDidMount、componentWillUnmount 和render,我只能让状态从 10 到 9“倒计时”。
两部分问题:我做错了什么?而且,有没有更有效的方法来使用 setTimeout(而不是使用 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;
【问题讨论】:
-
bind(this)不再需要,react 现在自己做。 -
你的定时器方法没有更新 currentCount
-
@Derek 你确定吗?我刚刚通过添加
this.timer.bind(this)让我的工作正常,因为 this.timer 本身不起作用 -
@Theworm @Derek 错了,有点。 React.createClass(已弃用)自动绑定方法,但
class Clock extends Component不会自动绑定。因此,是否需要绑定取决于您如何创建组件。
标签: javascript reactjs settimeout state