如何访问传递给反应子组件的嵌套 JSON graphql 对象,然后列出这些项目?

How to access nested JSON graphql object passed into react child component, then list those items?

GraphQL:

{
 "data": [ 
   "theProducts": { 
    "id": "1",
    "name": "Fitness bands",
    "resistanceLevels": {
         "UltraHeavy": 10,
         "Heavy": 8,
         "Medium": 6 },
    "prices": [
         16.8,
         24.9
         13.2   
           ]
      }  
   ] 
}

我正在尝试获取 resistanceBands JSON 对象和 price 数组以映射到 React 子组件(查询在父组件中定义)并呈现带项目符号的列表中的项目。

父组件:

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?  

子组件:

<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>

您需要对 prices 使用 .map(),因为这是一个数组:

<ul>
  {product.prices.map(p => <li>{p}</li>)}
</ul>

另外,对于 resistanceLevels,您可以使用 Object.keys and .map() 组合作为:

const resistanceLevels = {
   "UltraHeavy": 10,
   "Heavy": 8,
   "Medium": 6
};

const result = Object.keys(resistanceLevels)
                     .map(k => resistanceLevels[k]);

console.log(result);

阅读文档:

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.

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

我想这会让您了解如何根据 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>
   )
}