首页 > 解决方案 > 停止重新渲染反应功能组件

问题描述

我正在使用第三方组件,每次状态更改时都会重新渲染,这很好,但在某些情况下,即使状态发生更改,我也不希望它重新渲染。有没有办法使用反应功能组件。我在网上阅读过它说使用 shouldComponentUpdate() 但我正在尝试使用功能组件并尝试使用 React.Memo 但它仍然会重新渲染

代码

const getCustomers = React.memo((props) => {

useEffect(() => {

});

return (
<>
<ThirdPartyComponent>
do other stuff 
{console.log("Render Again")}
</ThirdPartyComponent>

</>
)
});

标签: reactjsreact-reduxreact-hooks

解决方案


对于道具:

如何实现 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 示例来看看这是否真的是你想要的。


推荐阅读