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

TypeScript中遍历对象无法返回JSX.Element的问题求助

解决方法:根据匹配key返回对应JSX.Element

问题根源

  1. 你调用Object.entries(CUSTOM_MAP).map()遍历对象,但没有接收或处理map的返回结果——map内部的return只是当前迭代函数的返回值,不会传递到外层functionName的返回值。
  2. 函数最后固定返回空的<></>,导致无论是否匹配到对应key,最终返回的都是空内容。

解决方案

方案一:直接通过对象键访问(最简洁高效)

利用对象的键值特性,直接用传入的errorStatus获取对应value,无需遍历:

const functionName = (errorStatus: string): JSX.Element => {
  // 用类型断言确保key属于CUSTOM_MAP的键类型
  const value = CUSTOM_MAP[errorStatus as keyof typeof CUSTOM_MAP];
  
  if (value) {
    return (            
      <>
        <div>
          Some html code with this {value}
        </div>
      </>
    );
  }
  
  // 匹配失败时的默认返回内容
  return <div>No matching status found</div>;
};

方案二:使用find遍历匹配(适合需额外逻辑的场景)

如果需要在遍历过程中添加额外判断逻辑,可以用find定位到目标键值对:

const functionName = (errorStatus: string): JSX.Element => {
  const matchedEntry = Object.entries(CUSTOM_MAP).find(([key]) => key === errorStatus);
  
  if (matchedEntry) {
    const [, value] = matchedEntry;
    return (            
      <>
        <div>
          Some html code with this {value}
        </div>
      </>
    );
  }
  
  // 匹配失败时的默认返回内容
  return <div>No matching status found</div>;
};

为什么原map写法无效?

map会返回一个数组,其中包含每个迭代的返回值(匹配时是JSX,不匹配时是undefined),但你既没有处理这个数组,还在函数末尾固定返回空Fragment,所以无法将匹配到的JSX传递到调用处。如果一定要用map,需要过滤掉undefined并返回数组中的有效元素,但这种方式冗余,远不如直接访问或find高效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:52:44