如何在React.js中正确展示JSON记录的所有子属性值
解决React中访问嵌套JSON字段的问题
嘿,我看你已经成功渲染出context和id字段啦!剩下的字段因为嵌套在多层对象和数组里,咱们只需要顺着数据结构一步步访问就能拿到它们~
先理清楚你的数据结构
每个results项里的service是一个数组,里面的对象又包含attributes,而你要的字段分散在attributes.main和attributes.additionalInformation里:
productname、price→obj.service[0].attributes.maincategories、tags、description→obj.service[0].attributes.additionalInformation
修改后的代码示例
把你的render方法里的列表项改成下面这样,就能显示所有需要的字段了:
render() { return ( <div> <ul> {this.state.rec.results.map((obj, i) => { // 先把嵌套的字段提取出来,让代码更清晰 const serviceAttr = obj.service[0].attributes; const mainInfo = serviceAttr.main; const additionalInfo = serviceAttr.additionalInformation; return ( <li key={i} style={{ marginBottom: '15px' }}> <p><strong>ID:</strong> {obj.id}</p> <p><strong>Context:</strong> {obj.context}</p> <p><strong>Product Name:</strong> {mainInfo.productname}</p> <p><strong>Price:</strong> {mainInfo.price}</p> <p><strong>Categories:</strong> {additionalInfo.categories.join(', ')}</p> <p><strong>Tags:</strong> {additionalInfo.tags.join(', ')}</p> <p><strong>Description:</strong> {additionalInfo.description}</p> </li> ) })} </ul> </div> ); }
几个小细节说明
为什么用
service[0]?
因为你的service是数组类型,每个results项里只有一个service对象,所以用索引0直接取第一个元素。如果以后service可能有多个项,你可以再嵌套一个map来遍历它。数组转字符串
categories和tags是数组,用join(', ')可以把数组元素转成逗号分隔的字符串,显示更友好。提取变量优化代码
把嵌套的字段提前提取成变量,避免重复写长长的访问路径,代码可读性会更高~
这样修改后,你就能看到所有需要的字段内容啦!
内容的提问来源于stack exchange,提问作者Nancy Moore
相关产品推荐
相关产品推荐

