更新渲染器里面的定时器会发出警告
问题描述:
我知道它给了我一个警告,因为它不纯。但是,当我把它放在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);
}
谢谢你的工作!有道理 –
@SinanSamet欢迎你好运! –