使用React.memo和useCallback防止函数引起重新渲染

时间:2019-10-17 18:49:56

标签: reactjs usecallback

我正在关注this tutorial,它与React.memo一起展示了react的'useCallback'钩子,以防止不必要地渲染函数。为了证明这一概念,我们使用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;

1 个答案:

答案 0 :(得分:0)

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

这意味着,如果仅渲染主组件而不渲染Button组件,则背景必须相同,但是由于每次都接收不同的背景色,所以没有意义。

如果道具发生更改(如果您未实现自定义的shouldUpdate生命周期方法),React将始终重新渲染组件。

相关问题