ReactJS中的列表和键:TypeError:无法读取未定义的属性'map'

问题描述 投票:0回答:1

我将一些HTML转换为ReactJS,而我正在尝试使用转换列表功能。我的意思是:https://reactjs.org/docs/lists-and-keys.html

非常感谢您的帮助。

我得到的错误是:TypeError:无法读取未定义的属性'map'编译器指出这一行是问题:

const menuPizzaList = props.pizzaItems.map((item) =>

这里是文件中的所有代码:


    import React from 'react';

    function PizzaList(props) {

        const menuPizzaList = props.pizzaItems.map((item) =>

            <div key={item.id}>
                <br />
                <h1><b>{item.title}</b><span className="w3-tag w3-red w3-round">{item.special}</span>
                    <span className="w3-right w3-tag w3-dark-grey w3-round">{item.price}</span></h1>
                <p className="w3-text-grey">{item.about}</p>
            </div>
        );

        return (
            <div>
                {menuPizzaList}
            </div>
        )

    }

    export default PizzaList; 

正在从数组中检索数据:


    //JSON object with menu items for pizza 
    const pizzaItems = [
        {id:1, title:'Margherita', price:'$12.50', about: 'Fresh tomatoes, fresh mozzarella, fresh basil'},
        {id:2, title:'Formaggio', price:'$15.50', about: 'Four cheeses (mozzarella, parmesan, pecorino, jarlsberg)'},
        {id:3, title:'Chicken', price:'$17.00', about: 'Fresh tomatoes, mozzarella, chicken, onions'},
        {id:4, title:'Pineapple"o"clock', price:'$16.50', about: 'Fresh tomatoes, mozzarella, fresh pineapple, bacon, fresh basil'},
        {id:5, title:'Meat Town', special: 'Hot!', price:'$20.00', about: 'Fresh tomatoes, mozzarella, hot pepporoni, hot sausage, beef, chicken'},
        {id:6, title:'Parma', special: 'NEW', price:'$21.00', about: 'Fresh tomatoes, mozzarella, parma, bacon, fresh arugula'}

    ];

然后将数据传递到此


    <PizzaList items={pizzaItems}></PizzaList>    

javascript arrays reactjs function react-component
1个回答
0
投票

更改<PizzaList items={pizzaItems}></PizzaList><PizzaList pizzaItems={pizzaItems}></PizzaList>


0
投票

您正在尝试在道具出现之前调用.map。最初渲染应用程序时,道具不存在,这就是为什么您会收到错误消息的原因。

import React from 'react';

function PizzaList(props) {
    const { pizzaItems } = props;

    const menuPizzaList = pizzaItems && pizzaItems.map((item) =>

        <div key={item.id}>
            <br />
            <h1><b>{item.title}</b><span className="w3-tag w3-red w3-round">{item.special}</span>
                <span className="w3-right w3-tag w3-dark-grey w3-round">{item.price}</span></h1>
            <p className="w3-text-grey">{item.about}</p>
        </div>
    );

    return (
        <div>
            {menuPizzaList}
        </div>
    )

}

export default PizzaList; 

如果更改为具有先检查pizzaItems是否存在的条件,那么您应该很好。

© www.soinside.com 2019 - 2024. All rights reserved.