[英]How to access nested JSON graphql object passed into react child component, then list those items?
GraphQL: GraphQL:
{
"data": [
"theProducts": {
"id": "1",
"name": "Fitness bands",
"resistanceLevels": {
"UltraHeavy": 10,
"Heavy": 8,
"Medium": 6 },
"prices": [
16.8,
24.9
13.2
]
}
]
}
I am trying to get the resistanceBands
JSON object and the price
array to map to the react child component (the query is defined in the parent component) and render the items in a list with bullet points.我正在尝试将
resistanceBands
JSON object 和price
数组 map 获取到反应子组件(查询在父组件中定义)并在带有项目符号的列表中呈现项目。
Parent Component:父组件:
const GET_PRODUCT_DATA = gql`
query getProducts {
theProducts {
id
name
resistanceLevels
prices
}
}
`
// How I am mapping data (name, etc) into the child component
const productsToRender = data.theProducts
{productsToRender.map( product => <ProductDisplay key={product.id} product={ product } />) }
// How can map the object and array to display their items to the ProductDisplay child component?
Child Component:子组件:
<div>
<h1>{product.name}</h1> // This works
<p>Resistance Levels | Intensity:</p>
<ul>
<li>{product.resistanceLevels}</li> // This doesnt
</ul>
<p>Prices</p>
<ul>
<li>{product.prices}</li> // This doesnt
</ul>
</div>
You need to use .map()
for prices
also because that's an array as:您还需要使用
.map()
作为prices
,因为这是一个数组:
<ul>
{product.prices.map(p => <li>{p}</li>)}
</ul>
Also for resistanceLevels
you can use Object.keys
and .map()
combination as:同样对于
resistanceLevels
,您可以使用Object.keys
和.map()
组合作为:
const resistanceLevels = { "UltraHeavy": 10, "Heavy": 8, "Medium": 6 }; const result = Object.keys(resistanceLevels).map(k => resistanceLevels[k]); console.log(result);
Read from the documentation:从文档中阅读:
The
Object.keys()
method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.Object.keys()
方法返回给定对象自己的可枚举属性名称的数组,迭代顺序与普通循环相同。
The
map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.map()
方法创建一个新数组,其中填充了对调用数组中每个元素调用提供的 function 的结果。
I guess this gives you the idea how to move further based on the example of prices.map()
.我想这会让您了解如何根据
prices.map()
的示例进一步前进。
const ParentComponent =()=>{
return(
<div>
{productsToRender.map(product => <ProductDisplay key={product.id} product={product }/>) }
</div>
)
}
export default ParentComponent;
const ProductDisplay =(props)=>{
return (
<div>
<h1>{product.name}</h1>
<p>Resistance Levels | Intensity:</p>
<ul>
{Object.entries(props.product.resistanceLevels).map(([key, value]) =>{
return(
<li>{key} : {value}</li>
)
})}
</ul>
<ul>
{
props.product.prices.map(item => {
<li>{item}</li>
})
}
</ul>
</div>
)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.