setInterval with setState in React

前端 未结 2 1298
闹比i
闹比i 2021-02-07 12:25

I have a timer using setInterval() in a React component and I\'m unsure what the best practices are in order to start and stop this interval in respect to using

2条回答
  •  醉酒成梦
    2021-02-07 12:57

    I think the biggest flaw here is that you're using state to store your interval. While technically possible, I see no reason why you would actually want to do that.

    Instead, just use a local variable to your component:

    startTimer(){
      if(!this.timerId){     
        this.timerId = setInterval(()=>{
          //your function
        }, 1000);
      }
    }
    
    stopTimer(){
      clearInterval(this.timerId);
    }
    

    So I don't think you need to use the state at all here for your timer. You have some other general questions in your post though that are related to state, and I'll try to answer those below. Just bear in mind that they are irrelevant in solving your particular issue.


    What have they've done to circumvent asynchronous issues with setState()?

    You can use a callback to execute code after the state has been set. There's a section of the official docs about this; here's what it says:

    The second parameter is an optional callback function that will be executed once setState is completed and the component is re-rendered.

    setState(nextState, callback);
    

    Which lifecycle methods would be best for this type of situation?

    The same section of the doc as above continues:

    Generally we recommend using componentDidUpdate() for such logic instead.

    If you have multiple setState in your function, and you want to execute specific code after a specific event, I think you're fine using the callback. For more general purposes use the life-cycle method above.

提交回复
热议问题