我正在尝试弄清楚为什么当我单击一个特定的组件时,它的同级组件也会呈现出来
function CountButton({increment, count, number}) {
console.log(`Render CountButton ${number}`)
return <button onClick={() => increment(count + 1)}>{count}</button>
}
function DualCounter() {
const [count1, setCount1] = React.useState(0)
const increment1 = React.useCallback(() => setCount1(c => c + 1), [])
const [count2, setCount2] = React.useState(0)
const increment2 = React.useCallback(() => setCount2(c => c + 1), [])
console.log('Render DualCounter')
return (
<>
<CountButton count={count1} increment={increment1} number={1} />
<CountButton count={count2} increment={increment2} number={2} />
</>
)
}我使用useCallback并传递这些函数,以避免在任何渲染中,函数引用将是不同的引用。
发布于 2021-02-22 03:37:52
您将在同级<CountButton />组件上看到重新呈现,因为每次单击按钮更新计数器时,实际上都是在更新父组件<DualCounter />中的状态值,这也会导致在该组件上重新呈现。
由于DualCounter被重新呈现,因此子组件也将被重新呈现,在本例中包括两个<CountButton />元素。
防止这种情况的一种解决方案是用React.memo()包装CountButton组件。这将防止在对属性值没有任何更改的组件上进行重新渲染。
示例如下:
function CountButton({increment, count, number}) {
console.log(`Render CountButton ${number}`)
return <button onClick={() => increment(count + 1)}>{count}</button>
}
const CountButtonMemo = React.memo(CountButton)
function DualCounter() {
const [count1, setCount1] = React.useState(0)
const increment1 = React.useCallback(() => setCount1(c => c + 1), [])
const [count2, setCount2] = React.useState(0)
const increment2 = React.useCallback(() => setCount2(c => c + 1), [])
console.log('Render DualCounter')
return (
<>
<CountButtonMemo count={count1} increment={increment1} number={1} />
<CountButtonMemo count={count2} increment={increment2} number={2} />
</>
)另一种解决方案是不对CountButton组件上的事件导致的每个更改更新DualCounter状态,这将停止在其兄弟组件上触发不需要的重新渲染。你可以直接在每个CountButton组件上处理状态,如果这对你的应用有意义的话。
或者,您可以使用React状态管理工具,例如Redux,它也解决了这个问题,它负责委托与组件本身分离的应用程序状态。
https://stackoverflow.com/questions/66306194
复制相似问题