其他分享
首页 > 其他分享> > reac中useCallback使用

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>
    )

}

效果:

标签:const,log,reac,useState,使用,console,useCallback,click
来源: https://www.cnblogs.com/malong1992/p/15361364.html