【问题标题】:Who to avoid re-renders in React when using conditional Render and children node prop谁在使用条件渲染和子节点道具时避免在 React 中重新渲染
【发布时间】:2022-06-15 06:42:18
【问题描述】:

我有一个组件,我重用了它的大部分逻辑。 我希望避免每次将鼠标悬停在父级上时都会重新渲染其子级组件:

const ReusableComponent = ({ conditional }) => {
  const [isHovered, setIsHovered] = useState(false);

  const AnotherReusableComponent = ({ children }) => (
    <div>{children}</div>
  );

  const renderComponent = () => {
    if (conditional) {
      return <ComponentA />;
    };

    return <ComponentB />;
  };

  return (
    <div>
      <title 
        onMouseEnter={() => setIsHovered(true)}
        onMouseLeave={() => setIsHovered(false)}
      >
        Menu
      </title>
      <div className={isHovered ? 'oneClass' : 'otherClass'}>
        <AnotherReusableComponent>
          {renderComponent()}
        </AnotherReusableComponent>
      </div>
    </div>
  );
}

注意事项:

  • ComponentA 和 ComponentB 根据类名显示/隐藏
  • onHover 事件切换类名
  • 试过memo,没用。
  • 重新渲染发生onHover

【问题讨论】:

  • 你试过useCallback吗?

标签: javascript reactjs react-props memo


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-07
  • 1970-01-01
  • 2020-12-21
  • 2020-05-04
  • 2020-12-13
相关资源
最近更新 更多