如何在React/Next.js中动态映射深层嵌套JSON数据生成组件?
解决方案
你遇到的核心问题是现有JSON结构里,国家对应的数组每个元素都多套了一层「城市名作为键」的对象,导致遍历的时候没法直接拿到城市属性。下面给两种可行方案:
方案1:调整JSON结构(更推荐,后续维护成本更低)
你可以直接把每个国家数组里的嵌套城市键去掉,把城市属性直接作为数组元素,调整后的JSON结构示例:
{ "netherlands": [ { "id": "amsterdam", "city_key": "amsterdam", "destination": "Amsterdam", "page_url": "/destinations/europe/netherlands/amsterdam-attractions-guide", // 剩余原有城市字段保持不变 }, { "id": "greater-amsterdam", "city_key": "greater_amsterdam", "destination": "Greater Amsterdam", // 剩余原有城市字段保持不变 } // 其余城市以此类推 ], // 其余国家以此类推 }
调整后你现有的上下层组件代码完全不需要修改,destinations.map 遍历中可以直接拿到所有城市属性,传递给DestinationCard也能正常接收使用。
方案2:不修改现有JSON结构,直接调整下层组件代码
如果你暂时不想调整JSON结构,只需要修改DestinationsPage组件内的map逻辑,取出每个对象里嵌套的城市属性即可:
{destinations.map((place) => { // 取出当前对象的第一个值,就是对应的城市属性对象 const cityInfo = Object.values(place)[0]; return ( <DestinationCard key={cityInfo.id} {...cityInfo} pageType="destinationsPage" /> ); })}
如果需要同时拿到城市的键名(比如amsterdam、greater_amsterdam这类字段),可以用Object.entries处理:
{destinations.map((place) => { const [cityKey, cityInfo] = Object.entries(place)[0]; // cityKey就是城市的键名,需要的话可以作为props传递给组件 return ( <DestinationCard key={cityInfo.id} {...cityInfo} cityKey={cityKey} pageType="destinationsPage" /> ); })}
补充说明:动态国家变量适配
后续你把placeName改成动态取值(比如从路由参数获取对应国家名)也完全兼容以上两种方案,只需要确保getStaticProps或者getServerSideProps里的对应取值逻辑正常即可。
内容的提问来源于stack exchange,提问作者paraguen
相关产品推荐
相关产品推荐

