简体   繁体   English

如何在具有命名导出的文件中使用 React.memo()?

[英]How to use React.memo() in a file with named exports?

I'm used to export default React.memo(SomeComponent);我习惯export default React.memo(SomeComponent); so React can memoize my components.所以 React 可以记住我的组件。

But in a file where I'm using named exports.但是在我使用命名导出的文件中。 How can I use React.memo() ?我该如何使用React.memo()

export { React.memo(MainPostTopic), React.memo(MainPostSubtopic) };

The line above doesn't work.上面的行不起作用。

EXAMPLE FILE示例文件

function MainPostTopic(props) {
  console.log('Rendering MainPostTopic...');
  return (
    <LS.Topic_H2 id={props.id}>
      {props.value}
    </LS.Topic_H2>
  );
}

function MainPostSubtopic(props) {
  console.log('Rendering MainPostSubtopic...');
  return (
    <LS.Subtopic_H3>
      {props.value}
    </LS.Subtopic_H3>
  );
}

export { MainPostTopic, MainPostSubtopic };

This is what I've ended up doing:这就是我最终做的:

const MainPostTopic = React.memo(
  function MainPostTopic(props) {
    console.log('Rendering MainPostTopic...');
    return(
      ...
    );
  }
);

const MainPostSubtopic= React.memo(
  function MainPostSubtopic(props) {
    console.log('Rendering MainPostSubtopic...');
    return(
      ...
    );
  }
);

export {MainPostTopic, MainPostSubtopic};

I kept the same name for the functions and the exports.我为函数和导出保留了相同的名称。

Try尝试

export const MemoMainPostTopic = React.memo(MainPostTopic);

or或者

const MainPostTopic = memo(() => {
 ...
})
export { MainPostTopic };

Exports that aren't default need to be named.需要命名非default导出。

const MemoizedMainPostTopic = React.memo(MainPostTopic)
export {MemoizedMainPostTopic};

You just need to give name to the object properties you are exporting.您只需要为要导出的对象属性命名。

const MainPostTopicComponent = React.memo(MainPostTopic);
const MainPostSubtopicComponent = React.memo(MainPostSubtopic)

export {
  MainPostTopicComponent,
  MainPostSubtopicComponent 
};

Hope this can help!希望这可以帮助!

Using memo with default:默认使用备忘录:

import { memo } from "react";
const Todos = ({ todos }) => {
  return (
    <>
      <h2>My Todos</h2>
      {todos.map((todo, index) => {
        return <p key={index}>{todo}</p>;
      })}
    </>
  );
};

export default memo(Todos);

Now only if the todos property changed the component will re-render现在只有当 todos 属性改变时组件才会重新渲染

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM