reactjs - 停止重新渲染反应功能组件
问题描述
我正在使用第三方组件,每次状态更改时都会重新渲染,这很好,但在某些情况下,即使状态发生更改,我也不希望它重新渲染。有没有办法使用反应功能组件。我在网上阅读过它说使用 shouldComponentUpdate() 但我正在尝试使用功能组件并尝试使用 React.Memo 但它仍然会重新渲染
代码
const getCustomers = React.memo((props) => {
useEffect(() => {
});
return (
<>
<ThirdPartyComponent>
do other stuff
{console.log("Render Again")}
</ThirdPartyComponent>
</>
)
});
解决方案
如何实现 shouldComponentUpdate?
你可以用 React.memo 包装一个函数组件来浅显地比较它的 props:
const Button = React.memo((props) => {
// your component
});
它不是 Hook,因为它不像 Hook 那样组成。React.memo 等价于 PureComponent,但它只比较 props。(您还可以添加第二个参数来指定一个自定义比较函数,该函数采用新旧道具。如果它返回 true,则跳过更新。)
对于状态:
没有内置的方法可以实现这一点,但您可以尝试将您的逻辑提取到自定义钩子中。这是我尝试仅在 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
);
setcount
在这种情况下,当且仅当shouldUpdate
返回 true时,才会发生重新渲染(由于使用)。即,当值是 4 的倍数并且前一个值不是 5 的倍数时。使用我的CodeSandbox 示例来看看这是否真的是你想要的。
推荐阅读
- python - 如何在无符号 dtypes 中将负值强制为 0?
- twilio - twilio 没有收到来自网站的消息
- visual-studio-code - Visual Studio代码集成终端无响应
- oracle - 更好的是在 for 循环中多次删除
- java - 如何在android webview中保存上次访问的url?
- aws-fargate - 如何将 Fargate 与 Media convert 连接起来?
- python - 如何比较python3中的两个csv文件?
- bash - 为什么此 YAD 列表代码无法正常工作?
- unix - Vim:在普通模式下切换键盘布局
- angular - Spring Gateway 如何路由深度 SPA 链接