我使用的是第三方组件,它在每次状态更改时重新渲染,这很好,但在某些情况下,即使状态更改,我也不希望它重新渲染。有没有办法使用 react 功能组件。我在网上看过它说使用 shouldComponentUpdate() 但我正在尝试使用功能组件并尝试使用 React.Memo 但它仍然重新呈现
代码
const getCustomers = React.memo((props) => {
useEffect(() => {
});
return (
<>
<ThirdPartyComponent>
do other stuff
{console.log("Render Again")}
</ThirdPartyComponent>
</>
)
});
最佳答案
如何实现 shouldComponentUpdate?
你可以用 React.memo 包装一个函数组件来浅比较它的属性:
const Button = React.memo((props) => {
// your component
});
它不是 Hook,因为它不像 Hook 那样组合。 React.memo 相当于 PureComponent,但它只比较 props。 (您还可以添加第二个参数来指定接受新旧 Prop 的自定义比较函数。如果它返回 true,则跳过更新。)
对于状态:
没有内置方法可以实现此目的,但您可以尝试将逻辑提取到自定义 Hook 中。这是我尝试仅在 shouldUpdate 返回 true 时才重新呈现。请谨慎使用它,因为它与 React 的设计目的相反:
const useShouldComponentUpdate = (value, shouldUpdate) => {
const [, setState] = useState(value);
const ref = useRef(value);
const renderUpdate = (updateFunction) => {
if (!updateFunction instanceof Function) {
throw new Error(
"useShouldComponentUpdate only accepts functional updates!"
);
}
const newValue = updateFunction(ref.current);
if (shouldUpdate(newValue, ref.current)) {
setState(newValue);
}
ref.current = newValue;
console.info("real state value", newValue);
};
return [ref.current, renderUpdate];
};
你会像这样使用它:
const [count, setcount] = useShouldComponentUpdate(
0,
(value, oldValue) => value % 4 === 0 && oldValue % 5 !== 0
);
在这种情况下,当且仅当 shouldUpdate
返回 true 时,才会发生重新渲染(由于 setcount
的使用)。即,当值是 4 的倍数且前一个值不是 5 的倍数时。玩我的 CodeSandbox example看看这是否真的是您想要的。
关于reactjs - 停止重新渲染 react 功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63470738/