You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何基于布尔值为数组find方法设置不同查询条件

调整方案

你的现有代码核心问题出在find的匹配规则错误:当前是把布尔类型的currencyCode标识和列表项的字符串类型货币代码做比对,完全没有用到传入的code参数,自然匹配不到正确结果。
调整后的完整代码如下:

// 若你未定义Props类型可先补全该部分
type Props = {
  code: string;
  currencyCode?: boolean;
  countryCode?: boolean;
  className?: string;
}

const CountryFlag = ({ code, currencyCode, countryCode, className }: Props) => {
  const countryEntry = flagsList.find((f) => {
    // 根据布尔标识选择对应字段和传入的code匹配
    if (currencyCode) {
      return f.currencyCode === code;
    }
    if (countryCode) {
      return f.countryCode === code;
    }
    // 兜底默认规则,可根据业务需求调整,这里默认按国家代码匹配
    return f.countryCode === code;
  });

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

  const FlagComponent = countryEntry.flagComponent;
  return (
    <StyledImageWrapper className={className}>
      <FlagComponent />
    </StyledImageWrapper>
  );
};

如果需要更严谨的参数校验,可以额外增加两个布尔标识同时为true的异常提示:

// 放在组件逻辑最开头即可
if (currencyCode && countryCode) {
  console.warn('CountryFlag组件不可同时将currencyCode和countryCode设为true,将默认按货币代码匹配');
  // 也可直接抛出错误或指定优先级更高的匹配字段
}

内容的提问来源于stack exchange,提问作者cts

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 02:15:02