javascript JS Map混淆

2skhul33  于 2023-04-19  发布在  Java
关注(0)|答案(1)|浏览(110)

尝试从数组中获取数据,收到错误.我已经将数据传入组件,并访问比萨饼的数据,这是一个数组.请帮助解决这个Map错误.什么做错了在这里Map?

const mockJson = {
        
                "pizza": [
                    {
                        "id": 0,
                        "name": "Margherita",
                        "description": "",
                        "ingredients": ["tomato sauce", "mozzarella"],
                        "spicy": false,
                        "vegetarian": true,
                        "price": 17.0,
                        "image": "https://i.imgur.com/8B8YLOo.jpg"
                    },
                    {
                        "id": 1,
                        "name": "Pepperoni",
                        "description": "",
                        "ingredients": ["tomato sauce", "mozzarella", "double pepperoni"],
                        "spicy": false,
                        "vegetarian": false,
                        "price": 20.0,
                        "image": "https://i.imgur.com/OHHctnf.jpg"
                    }
        ]
        
        const RestaurantCard = (data) => {
            console.log(data, 'data1') //data is reachable
         return (
           <>   
            <div className="res-card">
            {console.log(helo, 'data2')} 
              {data.pizza?.map((helo,id) => 
         
              {
              return (
                <p key={id}>{helo.name}</p>
                <p key={id}>{helo.name}</p>
                )
              }
                )}
               
              
            </div>
            </>
            ) 
        }
        
 ================================= 
const Body = () => {
            return (
                <>
                <div className="res-container"><RestaurantCard data={mockJson} />
                </div>
                
                </>
            )
        }

我无法获取{helo.name},我做错了什么?

5m1hhzi4

5m1hhzi41#

你应该销毁数据prop或者使用props接收它:
选择一:

// destructuring
const RestaurantCard = ({data}) => {
        console.log(data, 'data1') //data is reachable
     return (
       <>   
        <div className="res-card">
        {console.log(helo, 'data2')} 
          {data?.pizza?.map((helo,id) => 
     
          {
          return (
            <p key={id}>{helo.name}</p>
            <p key={id}>{helo.name}</p>
            )
          }
            )}
           
          
        </div>
        </>
        ) 
    }

选择二:

// accessing it as props
const RestaurantCard = (props) => {
        console.log(data, 'data1') //data is reachable
     return (
       <>   
        <div className="res-card">
        {console.log(helo, 'data2')} 
          {props?.data?.pizza?.map((helo,id) => 
     
          {
          return (
            <p key={id}>{helo.name}</p>
            <p key={id}>{helo.name}</p>
            )
          }
            )}
           
          
        </div>
        </>
        ) 
    }

相关问题