简体   繁体   中英

setState doesn't work in React when using setInterval

I am trying to update the currentNumber state when countUp function are triggered by setInterval() from worker.js. However, currentNumber state don't change from 0. Is there any way to update currentNumber state?

Test.js

import React from 'react';
import {useState, useEffect} from 'react'


const Test = () => {
    const [currentNumber, setcurrentNumber] = useState(0);


    function countUp() {
        console.log(currentNumber);
        
        var tmp = currentNumber + 1
        setcurrentNumber(tmp)  
        }
    

    useEffect(() => {
        var timerWorker; 
        timerWorker = new Worker('./worker.js');

        timerWorker.onmessage = function(f) {  
            if (f.data == "tick") {
            countUp();
                }
        }    
    }, []);
      
    return (
        <div className="app">
          {currentNumber}
        </div>
)}
export default Test;

worker.js

var interval=100;

setInterval(function(){postMessage("tick");},interval)
 

You can try like this, in Test.js: My english is not really good, so I can't explan it so much.

useEffect always cache state and reuse for its callback func, in this case is "currentNumber". So the "countUp" func always have currentNumber = 0. Only When dependencies has change, it will recreate its callback func and apply new state to it.

import {useState, useEffect, useRef} from 'react'    
const timerWorker = useRef(new Worker('./worker.js'));

const Test = () => {
    const [currentNumber, setcurrentNumber] = useState(0);

    const timerWorker = useRef(new Worker('./worker.js'));
    
    function countUp() {...}

    useEffect(() => {
        timerWorker.current.onmessage = function(f) {  
            if (f.data == "tick") {
               countUp();
            }
        } 
    }, [currentNumber])

    return (
        <div className="app">
          {currentNumber}
        </div>
    )

}

export default Test;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM