我发现您的代码有4个问题:
- 在计时器方法中,您始终将当前计数设置为10
- 您尝试在render方法中更新状态
- 您没有使用
setState
方法来实际更改状态 - 您没有在状态中存储intervalId
让我们尝试解决该问题:
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,则可以使用稍微修改的版本:
timer: function() { var newCount = this.state.currentCount - 1; if(newCount >= 0) { this.setState({ currentCount: newCount }); } else { clearInterval(this.state.intervalId); }},


