TypeError:无法读取 ReactJS 中未定义的属性“name”
2020-11-04
118
我正在尝试在 ReactJS 中制作一个动态汉堡构建器。主页一打开,就出现这样的错误:
TypeError: Cannot read property 'name' of undefined
IngredientsMenuItem
/src/components/IngredientsMenu/IngredientsMenuItem.js:18
15 | return (
16 | <ItemWrapper>
17 | <ItemContent>
> 18 | <h3>{item.ingredient.name}</h3>
| ^ 19 | <h4>{item.ingredient.price}</h4>
20 | <Counter
21 | value={item.qty}
我将我的汉堡保存在上下文中。
我的配料文件:
export const ingredients= [
{
name:"salad",
price:0.5,
},
{
name:"cheese",
price:0.4,
},
{
name:"meat",
price:1.3,
},
];
我的主页:
const Home = () => {
const {burger,updateBurger} = useContext(BurgerContext);
return (
<div>
{!burger.length && updateBurger(buildBurger(ingredients))}
<Burger/>
<IngredientsMenu
ingredients={ingredients}
/>
</div>
)
}
export default Home
我的 buildBurger 函数:
export const buildBurger = (ingredients) => {
return [
ingredients.map((ingredient) => (
{
qty:0,
ingredient: ingredient
}
))
]
}
我这样做是为了为初始状态下值为 0 的配料创建模板。
我的 IngredientsMenu:
const IngredientsMenu = ({ingredients}) => {
const {burger, updateBurger} = useContext(BurgerContext);
return (
<>
<Wrapper>
{burger.map((item) => (
<IngredientsMenuItem
item={item}
/>
))}
</Wrapper>
</>
)
}
export default IngredientsMenu
我的 IngredientsMenuItem:
const IngredientsMenuItem = ({item) => {
const {burger, updateBurger} = useContext(BurgerContext);
const handleIncrement = (burgerItem) => {
}
const handleDecrement = (burgerItem) => {
}
return (
<ItemWrapper>
<ItemContent>
<h3>{item.ingredient.name}</h3>
<h4>{item.ingredient.price}</h4>
<Counter
value={item.qty}
onIncrement={() => handleIncrement(item)}
onDecrement={() => handleDecrement(item)}
/>
</ItemContent>
</ItemWrapper>
)
}
export default IngredientsMenuItem
我看不出我的错在哪里。有谁可以帮忙吗?
1个回答
在您的组件
IngredientsMenuItem
上,
item
prop 可能为
null
或
undefined
。
考虑在您的组件内添加
console.log
指令以查看那里到底有什么。
如果您希望您的代码“永不中断”,您可以检查内容是否存在,如果不存在,则恢复为空对象,如下所示:
const IngredientsMenuItem = ({item) => {
const {burger, updateBurger} = useContext(BurgerContext);
const handleIncrement = (burgerItem) => {
}
const handleDecrement = (burgerItem) => {
}
const ingredient = (item && item.ingredient) || {};
// this can be replaced to a shorter version if you support the `?.` operator:
// const ingredient = item?.ingredient || {};
const qty = (item && item.qty) || 0;
return (
<ItemWrapper>
<ItemContent>
<h3>{ingredient.name}</h3>
<h4>{ingredient.price}</h4>
<Counter
value={qty}
onIncrement={() => handleIncrement(item)}
onDecrement={() => handleDecrement(item)}
/>
</ItemContent>
</ItemWrapper>
)
}
Sergio Moura
2020-11-04