简体   繁体   English

返回组件数组的 React 自定义钩子

[英]React Custom Hook that returns array of Components

Is this a bad pattern to use with custom hooks?这是与自定义钩子一起使用的错误模式吗?

I'm passing in an array and then looping over that to determine what components will be displayed.我传入一个数组,然后循环遍历它以确定将显示哪些组件。

import React from "react";
import { Image, Paragraph, Header } from "../../components/Blocks";

export const useBlocks = (blocks) => {
  const items = blocks.map((item: Item) => {
    switch (item.name) {
      case "image":
        return <Image key={item.order} data={item.data} />;
      case "paragraph":
        return <Paragraph key={item.order} data={item.data} />;
      case "heading":
        return <Header key={item.order} data={item.data} />;
      default:
        return null;
    }
  });

  return items;
};

Using hooks to return JSX isn't a common pattern.使用钩子返回 JSX 不是一种常见的模式。 For what you're describing a much more straightforward and more industry standard implementation would be to just create this as a component.对于您所描述的更直接且更符合行业标准的实现,只需将其创建为一个组件即可。

I extrapolated the switch logic to its own component incase there are needs to reuse this in other places of the application.我将 switch 逻辑外推到它自己的组件,以防需要在应用程序的其他地方重用它。 Also its easier to read and test behavior this way.这样也更容易阅读和测试行为。

import React from "react";
import { Image, Paragraph, Header } from "../../components/Blocks";

function BlockImage({item}) {
  switch (item.name) {
    case "image":
      return <Image data={item.data} />;
    case "paragraph":
      return <Paragraph data={item.data} />;
    case "heading":
      return <Header data={item.data} />;
    default:
      return null;
  }
}

export const Blocks = ({blocks}) => {
  return (
    <>
      {blocks.map((item: Item) => <BlockImage key={item.order} item={item} />}
    </>
  );
}

By implementing this hook I can tell that you are applying Factory Pattern通过实现这个钩子,我可以看出你正在应用工厂模式

Check this URL to get more details: https://refactoring.guru/design-patterns/factory-method检查此 URL 以获取更多详细信息: https : //refactoring.guru/design-patterns/factory-method

it's useful when it comes to loading dynamic components/classes in the runtime based on a given input.当基于给定的输入在运行时加载动态组件/类时,它很有用。 also if component creation is a little bit costly and you want to unify your solution, then it would good choice.此外,如果创建组件的成本有点高,并且您想统一您的解决方案,那么这也是不错的选择。

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

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