函数 setInterval 在 reactJs 中不起作用

Function setInterval is not working in reactJs

我想在 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)
}

注意:在 componentWillUnmount

中清除 setInterval