2016-12-04 50 views
0

我知道它给了我一个警告,因为它不纯。但是,当我把它放在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()没有警告关于它不是纯?

回答

1

看来你正在试图从数字每秒钟减少一个,所以你应该使用setinterval方法而不是settimeout来处理。如果将它添加到componentdidmount函数中,它将在初始渲染发生后立即开始下降。

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

谢谢你的工作!有道理 –

+0

@SinanSamet欢迎你好运! –