函数setInterval在reactJs中不起作用

瓦尔蒂卡·夏尔马

我想在React组件中经过一定时间间隔后调用某些函数并更新状态,但是它没有按预期工作。这是我的代码。

componentDidUpdate(){
        console.log("update")
        setInterval(this.tickingTimer(), 2000)
    }
    tickingTimer(){
        this.state.counter = this.state.counter+1
        console.log("timer");
    }

我也尝试在componentDidMount中设置间隔函数,但它仅调用一次。间隔后不更新数据。

Shubham Khatri

您不得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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章