[英]How do I use React.memo to prevent re-rendering?
I have two functional components.我有两个功能组件。 One keeps an incrementing number as state and displays it.一个保持递增的数字作为状态并显示它。 Its child is a button which receives the increment
function as a prop and calls it when clicked.它的子项是一个按钮,它接收increment
函数作为道具并在单击时调用它。
const IncrementButton = props => {
return <button onClick={props.increment}>Increment</button>;
};
const App = () => {
const [count, setCount] = React.useState(0);
const increment = () => setCount(count + 1);
return (
<div className="App">
<h1>{count}</h1>
<IncrementButton increment={increment} />
</div>
);
};
When App
re-renders, I want to avoid re-rendering IncrementButton
.当App
重新渲染时,我想避免重新渲染IncrementButton
。
The docs suggest using React.memo
to do this, but when I tried the below example, it didn't help.文档建议使用React.memo
来执行此操作,但是当我尝试以下示例时,它没有帮助。
const IncrementButton = React.memo(props => {
return <button onClick={props.increment}>Increment</button>;
});
Am I missing something?我错过了什么吗? What is the correct way to memoize a component so it doesn't re-render?记住组件以便它不会重新渲染的正确方法是什么?
The issue you have is that every time App rerenders, it creates a brand new increment function.您遇到的问题是,每次 App 重新渲染时,它都会创建一个全新的增量函数。 So every time Incrementbutton renders, it has a brand new props.increment.所以每次 Incrementbutton 渲染时,它都有一个全新的 props.increment。 As a result, React.memo doesn't really do anything, because the props keep changing, and so no renders can be skipped.结果,React.memo 并没有真正做任何事情,因为道具一直在变化,所以不能跳过渲染。
The fix for this is to make it so the increment function is not recreated every time.对此的解决方法是使增量函数不会每次都重新创建。 You can do this using useCallback, so a first pass might look like this:您可以使用 useCallback 执行此操作,因此第一遍可能如下所示:
const increment = useCallback(
() => setCount(count + 1),
[count]
)
This will create the increment function just once, and then memoize the result, until count change.这将只创建一次增量函数,然后记住结果,直到计数改变。 Unfortunately, count is the only thing that could really change anyway, so we end up having to recreate this function most of the time.不幸的是,count 是唯一可以真正改变的东西,所以我们最终不得不在大多数时候重新创建这个函数。 So we need to make another modification: instead of passing count +1 into setCount, setCount allows you to pass a function into it.所以我们需要做另一个修改:不是将 count +1 传递给 setCount,而是 setCount 允许您将函数传递给它。 This function will get called with the previous value, so that you can base the new value on it:此函数将使用先前的值调用,以便您可以基于它的新值:
const increment = useCallback(
() => setCount(oldCount => oldCount + 1),
[]
);
And now you have a increment function that's created only once ever, which in turn lets IncrementButton have no changes to its props, and thus React.memo can do its job and skip rerendering.现在你有一个 increment 函数,它只创建一次,这反过来让 IncrementButton 没有改变它的 props,因此 React.memo 可以完成它的工作并跳过重新渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.