App.js
importReact, { useState, memo, useCallback, useContext } from‘react’ // Home functionHome(props) { console.log(‘Home组件被渲染了’) return ( <div> <p>Home组件</p> <buttononClick={() => { props.handler() }}>减小</button> </div> ) } // About functionAbout(props) { console.log(‘About组件被渲染了’) return ( <div> <p>About组件</p> <buttononClick={() => { props.handler() }}>增加</button> </div> ) } const MemoHome = memo(Home) const MemoAbout = memo(About) //父组件重新渲染后,避免子组件也重新渲染 functionApp() { console.log(‘App组件被渲染了’) const [numState, setNumState] = useState(10) const [ageState, setAgeState] = useState(20) functionincrement() { setNumState(numState + 2) } // function decrement() { // setAgeState(ageState - 4) // } // 子组件控制父组件状态,不相关的子组件也会与父组件一起重新渲染,useCallback解决这个问题 constdecrement = useCallback(() => { setAgeState(ageState - 4) }, [ageState]) return ( <div> <p>num数据: {numState}</p> <p>age数据: {ageState}</p> <hr/> <MemoHome handler={decrement}/> <hr/> <MemoAbout handler={increment}/> </div> ) } exportdefaultApp