首页 > 解决方案 > 映射对象中的多个可能值 - React 组件

问题描述

我目前有一个组件,它接受一个 currencyCode 并返回相应国家的 SVG。我想扩展组件,以便我们希望按国家名称而不是货币代码进行搜索。当前传入组件的 props 是:

currencyCode - 类似于“AED”和 countryLabel - 类似于“阿拉伯联合酋长国”

import Afghanistan from "./CountryFlags/Afghanistan.js";
// condensed imports

const currencyCodeMap = {
  AED: UnitedArabEmirates,
  AFN: Afghanistan,
  ALL: Albania,
  AMD: Armenia,
  AOA: Angola,
  ARS: Argentina,
  AUD: Australia,
  AZN: Azerbaijan,
};

type Props = {
  currencyCode?: string,
  countryLabel?: string,
  className?: string,
};

const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
  const FlagComponent = currencyCodeMap[currencyCode];

  if (!FlagComponent) {
    return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
  }

  return (
    <StyledImageWrapper className={className}>
      <FlagComponent />
    </StyledImageWrapper>
  );
};

我试图将我的 currencyCodeMap 更新为:

AED | "United Arab Emirates"这样标签或代码都会返回一个标志,但没有乐趣。有什么建议么?

标签: javascriptreactjsobject

解决方案


AED | "United Arab Emirates"不是有效的 JavaScript 语法。

为什么没有像这样的对象:

type CountryEntry = {
  currencyCode: string,
  countryLabel: string,
  flagComponent: JSX.Element
}

然后有一个数组并用于.find()获取组件。

它看起来像这样:

import Afghanistan from "./CountryFlags/Afghanistan.js";

type Props = {
  currencyCode?: string,
  countryLabel?: string,
  className?: string,
};

type CountryEntry = {
  currencyCode: string,
  countryLabel: string,
  flagComponent: JSX.Element
}

const flags: CountryEntry[] = [
  { currencyCode: "AFN", countryLabel: "Afghanistan", flagComponent: Afghanistan },
/* ... */
];

const CountryFlag = ({ currencyCode, countryLabel, className }: Props) => {
  const countryEntry = flags.find(
    (f) => f.countryLabel === countryLabel || f.currencyCode === currencyCode
  );

  if (!countryEntry) {
    return <StyledIcon isOberonIcon={true} name={"countryFallback"} />;
  } else {
    const FlagComponent = countryEntry.flagComponent;
    
    return (
      <StyledImageWrapper className={className}>
        <FlagComponent />
      </StyledImageWrapper>
    );
};

推荐阅读