【问题标题】:Why is my react.memo not working? How to properly memoize a child's child?为什么我的 react.memo 不起作用?如何正确记忆孩子的孩子?
【发布时间】:2021-10-21 06:03:45
【问题描述】:

据我了解,当 CIsTrue 状态更新时,带有“SecondButton”的 ToolbarButton 不应该重新渲染。但是,当我检查控制台日志时,它会重新渲染。我错过了什么?它与作为 React 组件的 Icon 道具有关吗?我试图在 React.memo 函数中添加一个检查来比较它们,但我不确定这是否足够。

function App() {

  const [AIsTrue] = useState(true);
  const [BIsTrue] = useState(true);
  const [CIsTrue] = useState(true);

  return (
       <ToolbarComponent
            AIsTrue={AIsTrue}
            BIsTrue={BIsTrue}
            CIsTrue={CIsTrue}
        />
  );
}

export default App;

import { ReactComponent as MyIcon } from 'somepath.svg';
import { ReactComponent as MyOtherIcon } from 'somepath2.svg';

export interface ToolbarComponentProps {
  AIsTrue: boolean;
  BIsTrue: boolean;
  CIsTrue: boolean;
}

export const ToolbarComponent: React.FunctionComponent<ToolbarComponentProps> = (props) => {
  const { AIsTrue, BIsTrue, CIsTrue } = props;

  return (
    <Stack>
      <ToolbarButton
        text="FirstButton"
        icon={<MyIcon />}
        visible={AIsTrue || BIsTrue || CIsTrue }
      />

      <ToolbarButton
        text="SecondButton"
        icon={<MyOtherIcon />}
        visible={BIsTrue}
      />

    </Stack>
  );
};

    export interface IToolbarButtonProps {
       text?: String;
       icon: React.ReactNode;
       visible?: Boolean;
    }

    export const ToolbarButton: React.FunctionComponent<IToolbarButtonProps> = React.memo(
      (props) => {
    const { text, icon, visible } = props;
    if (visible) {
       buttonClass = blah
    }

    console.log('I rendered - ' + text);

    return (
      <Button className={buttonClass}>
        <Stack horizontal>
          {icon}
          <Text>{text}</Text>
        </Stack>
      <Button>
    );
  },
  (prevProps, nextProps) => {
    if (prevProps.icon === nextProps.icon) {
      return true; // props are equal
    }
    return false; // props are not equal -> update the component
  },
);

【问题讨论】:

  • 您好,能否请您在在线 IDE 中分享一个最低可重现的代码/示例,如代码框 - 这将有助于社区快速解决它。

标签: reactjs react-hooks memoization react-tsx


【解决方案1】:

我不确定,但也许它正在重新渲染:

icon={<MyOtherIcon />}

尝试评论它一段时间并检查它是否解决了问题。 JSX 返回的任何内容都可能是每个渲染上的不同引用。


要修复它,请尝试传递为

icon={MyOtherIcon}

然后你可以在你的组件中render

let Icon = props.icon;
<Icon/>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-24
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2014-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多