reactjs - 带有查找条件的 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" 对不起,我是新来的反应
解决方案
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}`);
推荐阅读
- vb.net - DNN NavigateURL 在基本的 9.5.1 解决方案中导致警告?
- corda - 由于 java.io.NotSerializableException,无法启动我的自定义流程
- java - 在给定条件下查找坐标位于圆内
- java - Drools 引擎和数据库的区别
- javascript - RxJs | 如何将“mergeMap”延迟到前一个内部可观察对象完成的时刻?
- python-3.x - 无法将 pandas 类型从“对象”转换为“字符串”
- python - 加快 Python 中的正则表达式匹配
- android - Flutter 发布 apk 不起作用 - 只是白屏
- sql - 通过 T-SQL 以 JSON 格式导出数据映射
- python - 在对数比例图中绘制最小二乘回归线