简体   繁体   English

使用 React.memo 和 useCallback 防止函数导致重新渲染

[英]Using React.memo and useCallback to prevent functions from causing re-renders

I am following this tutorial demonstrating react's 'useCallback' hook along with React.memo to prevent a function being render unnecessarily.我正在按照本教程演示 react 的“useCallback”钩子以及 React.memo,以防止 function 被不必要地渲染。 To prove the concept we use useRef to console the number of renders.为了证明这个概念,我们使用 useRef 来控制渲染的数量。 This worked with the function alone but i added a function to randomize the button background color and I can't seem to no prevent the rendering of both functions.这仅与 function 一起使用,但我添加了 function 以随机化按钮背景颜色,我似乎无法阻止这两个功能的呈现。

    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;

It the example in the video you mentioned, the Button component does not change, because the props stay the same all the time.在您提到的视频中的示例中,Button 组件不会更改,因为道具始终保持不变。 In your example, the increment stays the same, but the problem is that the bgColor changes with each click.在您的示例中, increment保持不变,但问题是每次单击时bgColor发生变化。

That means, that if you rendered only the main component and not the Button component, the background would have to be the same, but because it receives different background color each time, it would not make sense.这意味着,如果您只渲染主组件而不渲染 Button 组件,则背景必须相同,但因为它每次接收不同的背景颜色,这将没有意义。

React will always re-render the component if the props change (if you don't implement custom shouldUpdate lifecycle method).如果 props 发生变化,React 总是会重新渲染组件(如果你没有实现自定义的 shouldUpdate 生命周期方法)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 React.memo 和 React.useCallback 防止重新渲染 - Prevent re-render using React.memo and React.useCallback React 的 Context API 重新渲染所有包装在 Context 中的组件,即使使用了 React.Memo API - React's Context API re-renders all components that are wrapped inside the Context even after using the React.Memo API React dnd 使用自定义拖动层重新渲染太多,react.memo - React dnd too many re-renders with custom drag layer, react.memo React Native - FlatLists 重新呈现记忆化组件(React.memo 不起作用) - React Native - FlatLists re-renders memoized components (React.memo not working) 嵌套组件中的 React.memo 从不调用 areEqual,总是重新渲染 - React.memo inside nested component never calls areEqual, always re-renders React.memo 重新渲染递归组件而不运行 areEqual function - React.memo re-renders recursive components without running the areEqual function React.memo 不阻止重新渲染不接受任何道具的无状态功能子组件 - React.memo Not Preventing Re-renders of Stateless Functional Child Component that Takes In No Props 使用 useCallback 和 useMemo 在 React 中重新渲染的问题 - Problem with re-renders in React with useCallback and useMemo 为什么在 React 中,当父组件重新渲染时子组件不重新渲染(子组件未被 React.memo 包装)? - Why, in React, do children not re-render when parent component re-renders(children are not wrapped by React.memo)? 在没有 React.memo 的情况下使用 useCallback 有什么好处吗? - is there any benefit of using useCallback without React.memo?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM