【问题标题】:Using React.memo and useCallback to prevent functions from causing re-renders使用 React.memo 和 useCallback 防止函数导致重新渲染
【发布时间】:2019-10-17 18:49:56
【问题描述】:

我正在关注 this tutorial 演示 react 的 'useCallback' 钩子以及 React.memo 以防止函数被不必要地渲染。为了证明这个概念,我们使用 useRef 来控制渲染次数。这仅适用于该功能,但我添加了一个随机化按钮背景颜色的功能,我似乎无法阻止这两个功能的呈现。

    import React,{useState, useCallback, useRef} from 'react';
import './App.css';

const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`

const Button = React.memo(({increment, bgColor}) => {
const count = useRef(0)
console.log(count.current++)
return(
    <button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
  )
})

const App = React.memo(() => {
  const [count, setCount] = useState(0)
  const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)



  const increment = useCallback(() => {  
    setCount(previousCount => previousCount + 1)
    setColor(randomColor)
  },[setCount,setColor])

  return (
    <div className="App">
      <header className="App-header">
        <h2>{count}</h2>
        <Button increment={increment} bgColor={color}>increment</Button>
      </header>
    </div>
  );
})

export default App;

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    import React,{useState, useCallback, useRef} from 'react';
    import './App.css';

    const randomColor = () => `rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`

    const Button = React.memo(({increment, bgColor}) => {
    const count = useRef(0)
    console.log(count.current++)
    return(
        <button onClick={increment} style={{backgroundColor: bgColor}}>increment</button>
      )
    })

    const App = React.memo(() => {
      const [count, setCount] = useState(0)
      const [color, setColor] = useState(`rgb(${Math.random()*255},${Math.random()*255},${Math.random()*255}`)



      const increment = useCallback(() => {  
        setCount(previousCount => previousCount + 1)
        setColor(randomColor)
      },[setCount,setColor])

      return (
        <div className="App">
          <header className="App-header">
            <h2>{count}</h2>
            <Button increment={increment} bgColor={color}>increment</Button>
          </header>
        </div>
      );
    })

    export default App;

【问题讨论】:

  • 能发一下useRandomColor的源码吗?
  • 抱歉刚刚添加到代码库中

标签: reactjs usecallback


【解决方案1】:

您提到的视频中的示例,Button 组件不会更改,因为道具始终保持不变。在您的示例中,increment 保持不变,但问题是 bgColor 随每次点击而变化。

也就是说,如果只渲染主组件而不渲染 Button 组件,则背景必须相同,但由于每次接收到不同的背景颜色,就没有意义了。

如果 props 发生变化,React 总是会重新渲染组件(如果你没有实现自定义的 shouldUpdate 生命周期方法)。

【讨论】:

  • 现在解释一下就说得通了。当然,组件必须重新渲染才能使颜色发生变化。感谢您的宝贵时间
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多