我看到你的代码有4个问题:
setState
我们试着解决这个问题:
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); } },
使用更新的10秒倒计时 class Clock extends Component
class Clock extends Component
import React, { Component } from 'react'; class Clock extends Component { constructor(props){ super(props); this.state = {currentCount: 10} } timer() { this.setState({ currentCount: this.state.currentCount - 1 }) if(this.state.currentCount < 1) { clearInterval(this.intervalId); } } componentDidMount() { this.intervalId = setInterval(this.timer.bind(this), 1000); } componentWillUnmount(){ clearInterval(this.intervalId); } render() { return( <div>{this.state.currentCount}</div> ); } } module.exports = Clock;
使用更新的10秒倒计时 的 钩 强> (一个新的功能提议,允许您使用状态和其他React功能而无需编写类。它们目前在React v16.7.0-alpha中)。
import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; const Clock = () => { const [currentCount, setCount] = useState(10); const timer = () => setCount(currentCount - 1); useEffect( () => { if (currentCount <= 0) { return; } const id = setInterval(timer, 1000); return () => clearInterval(id); }, [currentCount] ); return <div>{currentCount}</div>; }; const App = () => <Clock />; ReactDOM.render(<App />, document.getElementById('root'));