Anti-shake
Anti-shake means that the function can only be executed once within n seconds after the event is triggered. If the event is triggered again within n seconds, the function execution time will be recalculated.
Some input boxes in the project need to be anti-shake processing to prevent requests or judgments from being made every input, that is, reduce the trigger frequency to improve performance and avoid waste of resources.
1. Class component version
//The anti-shake methodconst debounceOther = (func, wait = 800) => { let timeout; // Timer variable return function () { clearTimeout(timeout); // Clear the last timer every time it is triggered, and then re-time it timeout = setTimeout(() => { func(arguments); }, wait); // After specifying xx ms, trigger the actual operation handler }; };
Many methods or events with high reusability are often encapsulated in projects and then introduced on the page
example:
Just look at the following examples to getInputValue and inputChange
This is a pop-up component based on antd package. In the input box, you need to determine whether it is repeated with the original value after input. If you do not perform anti-shake processing, you can enter it once and judge it once.
Here is the js file with encapsulated debounceOther function that is directly introduced into this component.
import { debounceOther } from "........."; class RelationModal extends Component { state = { visible: false, inputErr: '', inputValue: '' }; getInputValue = debounceOther(() => { let { specSelect } = ; //Original data //Is the same exist? let index = (item => === ); ({ inputErr: index === -1 ? "" : 'Node name is not allowed to be duplicated' }) },500) //After getting the inputValue input input box, there is a change of 500 milliseconds, call the anti-shake method inputChange = e => { ({ inputValue: },()=>{ () }) }; }
2. Function component version
The function of useCallback is actually to avoid unnecessary reRenders for subcomponents.
import {useRef,useCallback,useEffect} from 'react' function useDebounce(fn,delay,setval){ const {current}=useRef({fn,timer:null}) useEffect(()=>{ =fn },[fn]) return useCallback((e)=>{ setval() if(){ clearTimeout() } =setTimeout(()=>{ (e) },delay) }) } export default useDebounce
Call
import debounce from '../utils/debounce' import {useState} from 'react' function My(){ let [val,setval]=useState('') const inputval=debounce(()=>{ (val); },1000,setval) return <div> <input type="text" value={val} onChange={(e)=>inputval(e)}/> </div> } export default My
This is the end of this article about the anti-shake processing project of react component packaging input box. For more related anti-shake content of react input box, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!