reac中useCallback使用


import React,{useState,useCallback} from "react"
const Son = React.memo( ({a,c}) =>{
    console.log('son 重新渲染');
    return (
        <div>
            a:{a}
            <button onClick={c}>点击</button>
        </div>
    )

}) 
export default function useCallBack(){
    const [a, setA] = useState(0);
    const [b, setB] = useState(0);

    // const memoHandClick = () => console.log("click");
    const memoHandClick =useCallback(() =>{console.log("click")},[]) //避免的重新生成回调函数 保证了Son组件的重新渲染

    return(
        <div>
            {console.log('UseCallBack 渲染')}

            <Son a={a} c={memoHandClick} />
   
            <button onClick={() =>{setA(a +1 )}}>改变A</button>
            <button onClick={() =>{setB(b +1 )}}>改变B</button>
            <button onClick={memoHandClick}>click</button>

        </div>
    )

}

效果:
reac中useCallback使用

上一篇:docker container 内部相互调用 :same host


下一篇:react中useCallback使用案例