reactjs - 停止重新渲染 react 功能组件

标签 reactjs react-redux react-hooks

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

代码

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

useEffect(() => {

});

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

</>
)
});

最佳答案

For props:

如何实现 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/

相关文章:

javascript - React : Component with just a form, 表单提交操作因组件的使用者而异

reactjs - 路由更改时状态不会重置 - React-redux-router

reactjs - 与路由器 v5 发生 react 错误 : Objects are not valid as a React child (found: object with keys {children})

reactjs - Typescript - 返回泛型函数的函数 - 它有什么作用?

javascript - 不可变的 js Map() - 不理解 take() 和 skip()

javascript - 第二次 ajax 调用后 React.js 状态日期变得正确

Javascript:将动态对象的值合并到另一个对象的数组中

reactjs - 如何在 react 中增加和减少状态值?

javascript - React hooks - useState() 不会使用新的状态更新重新渲染 UI

reactjs - 将数组传递给组件