function CountBtn1({ onClick, count }) {
console.log('CountBtn1 render')
return <button onClick={onClick}>{count}</button>
}
function CountBtn2({ onClick, count }) {
console.log('CountBtn2 render')
return <button onClick={onClick}>{count}</button>
}
function Counter() {
const [count1, setCount1] = React.useState(0)
// const increment1 = () => setCount1(c => c + 1)
const increment1 = React.useCallback(() => setCount1(c => c + 1), [])
const [count2, setCount2] = React.useState(0)
// const increment2 = () => setCount2(c => c + 1)
const increment2 = React.useCallback(() => setCount2(c => c + 1), [])
return (
<>
<CountBtn1 count={count1} onClick={increment1} />
<CountBtn2 count={count2} onClick={increment2} />
</>
)
}
当我点击Button1时也会渲染
日志是
CountBtn1渲染
CountBtn2渲染
我的useMemo useCallback不会减少渲染次数。使用useMemo和useCallback的正确方法是什么?
答案 0 :(得分:1)
用备忘录包装组件:
const CountBtn1 = React.memo(function CountBtn1({ onClick, count }) {
console.log('CountBtn1 render')
return <button onClick={onClick}>{count}</button>
})
const CountBtn2 = React.memo(function CountBtn2({ onClick, count }) {
console.log('CountBtn2 render')
return <button onClick={onClick}>{count}</button>
})