preface

As I have react experience before, my colleagues asked me some questions when I was working on react project. Some of the questions were common, but they were almost forgotten after a long time. Here I take this opportunity to summarize briefly

Problem a:

How to ensure that each execution of timers (setTimeout and setInterval) has the same interval with the next execution, no matter how long the previous execution took

Scenario: if you need to initiate and respond a request every second, no matter how long it takes for the first request to complete, such as 200ms, the next request must be 1000ms later than the first one (i.e., the second request is initiated at 1200ms instead of 800ms), and so on

Idea 1: Considering the re-timing, it should be possible to achieve through anti-shake, and it is feasible to check online, but also provides idea 2 before:

useEffect(() = >{
    const timer=setInterval(() = >{
        Ajax();// Initiates an asynchronous operation
    },1000)
    return () = >{clearInterval(timer)}; }, [])Copy the code

After modification:

useEffect(() = >{
    debounce(Ajax,1000); }, [])Copy the code
// The buffeting function
const debounce = function (fn,delay){
    let timer;// Declare a timer
    return function(){
        let _this = this; 
        clearTimeout(timer);
        timer = setTimeout(() = >{
            fn.apply(_this);
        },delay)
    } 
} 
Copy the code

SetTimeout (fn, 0) can delay the execution of the code until the specified time, so that when the first execution is completed, it can delay the execution of the second time after 1000ms:

useEffect(() = >{
    const timer=setInterval(() = >{
        Ajax();// Initiates an asynchronous operation
    },1000)
    return () = >{clearInterval(timer)}; }, [])Copy the code

After modification:

useEffect(() = >{
    let timer = setTimeout(function Ajax(){
        / /...
        timer = setTimeout(Ajax,1000);
    },1000)
},[])
Copy the code

Problem two:

React-hooks useState is an asynchronous operation. How do I get the updated State in real time?

Idea 1: useEffect

useEffect(() = >{
    setState(state);
},[state]);
Copy the code

The useRef returns a mutable ref object whose.current property is initialized to the passed parameter (initialValue) and the ref object returned remains unchanged for the lifetime of the component

const [state,setState]=useState(' ')
const modelRef = useRef(null);

useEffect(() = >{
    // Each update assigns the value to modelRef
    modelRef.current = state;
},[state]);UseEffect is triggered when state changes

function handleChange(newState){
    setState(newState);UseEffect is triggered when state changes
    setTimeout(getState, 0);// It is important to set a 0ms delay
} 

function getState(){
    console.log(modelRef.current);// Get the latest value
}
Copy the code

Get multiple latest values at the same time

const changeSelectRef = useRef({
    "status": ""."modelStatus": ""."keyWord": ""
});
useEffect(() = >{
    changeSelectRef.current = {
        "status": status,
        "modelStatus": modelStatus,
        "keyWord": keyWord
    };
}, [status, modelStatus, keyWord]);
Copy the code

Reference:

www.jsphp.net/js/show-9-1…

Javascript.ruanyifeng.com/advanced/ti…

Blog.csdn.net/hl971115/ar…

Segmentfault.com/a/119000002…

Segmentfault.com/a/119000003…