2016-12-04 38 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歡迎你好運! –

相關問題