我想在React组件中经过一定时间间隔后调用某些函数并更新状态,但是它没有按预期工作。这是我的代码。
componentDidUpdate(){
console.log("update")
setInterval(this.tickingTimer(), 2000)
}
tickingTimer(){
this.state.counter = this.state.counter+1
console.log("timer");
}
我也尝试在componentDidMount中设置间隔函数,但它仅调用一次。间隔后不更新数据。
您不得setState
更改状态,而应使用状态更新。另外,一定不能在componentDidUpdate
中间直接使用间隔。具有间隔的最佳位置是,componentDidMount
并且不得触发setInterval的回调函数,而应将其作为参考传递。
componentDidMount(){
console.log("update")
this.timerId = setInterval(this.tickingTimer, 2000)
}
tickingTimer(){
this.setState(prev => ({counter: prevState.counter+1}));
console.log("timer");
}
componentWillUnmount() {
clearInterval(this.timerId)
}
注意:清除setInterval中 componentWillUnmount
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句