React中如何根据ID匹配数组元素并渲染对应文章详情内容
问题修复方案
核心错误点
- 匹配逻辑中你将路由拿到的
id字符串用{}包裹后变成了对象,字符串和对象做相等判断永远返回false,导致始终匹配不到文章 - 你的
posts数组结构不统一,部分文章的idSlug存放在content属性下,部分直接存放在文章对象顶层,匹配时没有做兼容处理 - 你用了
filter方法做匹配,返回的是数组,单条文章匹配用find方法更合适,直接返回匹配到的对象
修正后的代码
只需要修改Child组件的逻辑即可:
function Child() { const { id } = useParams(); // 兼容两种结构的idSlug取值,做匹配 const itemPost = posts.find(displayPost => { const postSlug = displayPost.idSlug || displayPost.content?.idSlug; return postSlug === id; }); // 匹配不到文章的兜底展示 if (!itemPost) return <div>未找到对应文章</div> // 统一取文章名称,兼容两种结构 const postName = itemPost.content?.name || itemPost.name; return ( <div> <div className="single-container rev-block"> <div className="single-content-container"> <h1>Title : {postName}</h1> {/* 后续你可以在这里加更多文章字段的渲染,比如封面图:<img src={itemPost.source} alt={postName} /> */} </div> </div> </div> ); }
可选优化建议
如果可以的话建议统一posts数组的结构,要么所有文章的基础属性都放在content下,要么都放在顶层,避免后续维护再出现类似的兼容问题。
内容的提问来源于stack exchange,提问作者leoop0
相关产品推荐
相关产品推荐

