首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >避免使用`useCallback`重新呈现

避免使用`useCallback`重新呈现
EN

Stack Overflow用户
提问于 2021-02-22 03:22:51
回答 1查看 1.4K关注 0票数 0

我正在尝试弄清楚为什么当我单击一个特定的组件时,它的同级组件也会呈现出来

代码语言:javascript
复制
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并传递这些函数,以避免在任何渲染中,函数引用将是不同的引用。

EN

回答 1

Stack Overflow用户

发布于 2021-02-22 03:37:52

您将在同级<CountButton />组件上看到重新呈现,因为每次单击按钮更新计数器时,实际上都是在更新父组件<DualCounter />中的状态值,这也会导致在该组件上重新呈现。

由于DualCounter被重新呈现,因此子组件也将被重新呈现,在本例中包括两个<CountButton />元素。

防止这种情况的一种解决方案是用React.memo()包装CountButton组件。这将防止在对属性值没有任何更改的组件上进行重新渲染。

示例如下:

代码语言:javascript
复制
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,它也解决了这个问题,它负责委托与组件本身分离的应用程序状态。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66306194

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档