在渲染器中更新计时器会发出警告

Updating timer inside render gives warning

我知道它给了我一个警告,因为它不纯。但是当我把它放在 componentDidMount() 中时,它不会更新。只减少一次。

这是我的:

class timer extends Component {
  constructor(props) {
    super(props);

    this.state = {
      seconds: 900
    };

  }

  render() {
    setTimeout(() => {
      if(this.state.seconds > 0){
        this.setState({seconds: this.state.seconds-1})
      }
    }, 1000);
  }
}

如何在其他地方更新状态,同时仍然能够使用 setTimeOut() 而没有警告它不是纯的?

您似乎正试图每秒从数字中减一,因此您应该使用 setinterval 方法而不是 settimeout 来处理它。如果将它添加到 componentdidmount 函数中,它将在初始渲染发生后立即开始减少。

componentDidMount(){
    this.setInterval( () => { 
        if(this.state.seconds > 0){
        this.setState({seconds: this.state.seconds-1})
           })
        }, 1000);
}