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

React中如何从患者嵌套的亲属数组匹配ID获取关联关系值

多层嵌套数组匹配实现方案

核心逻辑

由于relativeId具备唯一性,匹配结果最多只有一条,优先用Array.prototype.find方法:找到第一个符合ID匹配的项就终止遍历,比filter性能更优。

具体实现

方案1:内联直接渲染(适合当前页面仅单次使用的场景)

直接在遍历当前患者对象的逻辑中完成匹配,加空值兜底避免报错,替换你代码中注释的位置即可:

props.data.slice(0, props.n).map((item) => {
    // 匹配当前患者relatives数组中ID对应目标ID的项,可选链避免relatives为空时报错
    const matchedRelation = item.relatives?.find(rel => rel.id === 你存储的目标ID变量);
    return (
        <Grid item xl={4} md={4} xs={4}>
            <Link to={`/patient/${item.id}`} style={{ textDecoration: 'none', color: theme.palette.text.primary }}>
                <Card boxShadow={3} key={item.id} style={{ backgroundColor: theme.palette.card }}>
                    <CardImg src={item.imgUri} alt={item.name} onError={addDefaultSrc} />
                    {/* 匹配到就展示关系,没匹配到展示兜底文本 */}
                    <p style={{ padding: '0 16px', margin: '8px 0' }}>
                        {matchedRelation?.relationship ?? '暂无关联'}
                    </p>
                </Card>
            </Link>
        </Grid>
    )
})

注意:把代码里的「你存储的目标ID变量」替换成你实际存储该值的变量即可(比如props.targetId、this.state.targetId、路由参数等)。

方案2:封装通用工具函数(适合多处复用的场景)

如果项目里其他页面也需要做同类匹配,封装成独立工具函数更易维护:

// utils/patientRelation.js
export const getMatchedRelationship = (patientData, targetRelativeId) => {
  // 空值兜底:患者无relatives字段、匹配不到都返回默认值
  return patientData?.relatives?.find(rel => rel.id === targetRelativeId)?.relationship ?? '暂无关联';
}

在页面中引入后直接调用即可:

// 替换原来的内联匹配逻辑
const relationText = getMatchedRelationship(item, props.targetId);

注意事项

  • 必须做空值兜底:不要直接渲染matchedRelation.relationship,如果匹配不到会输出undefined,影响页面展示甚至触发错误。
  • 可选链?.兼容性:如果项目需要兼容IE等低版本浏览器,替换为常规判空逻辑即可:item.relatives && item.relatives.find(rel => rel.id === targetId)。
  • 你当前代码里key写在Card节点上是符合规范的,只要保证map遍历的同级元素key唯一即可,不需要调整位置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 02:06:02