首页 > 解决方案 > 带有查找条件的 React 中的 map()

问题描述

我有以下代码,其中 ItemNamesAndIds 是名称和 id 的数组如果 id 在方案中不存在,则系统崩溃并出现错误 TypeError: Cannot read property 'Name' of undefined

const items = x.ItemNamesAndIds
          .map((id) => schemes.find((x) => x.id === id).Name)
          .reduce((acc, cur) => `${acc}, ${cur}`);

如何在同一行中添加一个条件来说出类似 if Name === "undefined" then Name = "empty" 对不起,我是新来的反应

标签: reactjsdictionary

解决方案


const items = x.ItemNamesAndIds
      .map((id) => {
        const matchedSchemes = schemes.find((x) => x.id === id);

        if (matchedSchemes.length !== 0) {
            return matchedSchemes.Name;
        } else {
            return 'undefined';
        }
      })
      .reduce((acc, cur) => `${acc}, ${cur}`);

推荐阅读