我有一个名为 products 的数组对象,我正在循环它并将该数组作为道具传递给 Product 组件。
import React from 'react';
import {Grid} from '@material-ui/core';
import Product from './Product/Product'
const Products = () => {
const products = [
{id: 1, name: 'Shoes', description: 'running shoes', price: 1.5},
{id: 2, name: 'Macbook', description: 'Apple macbook', price: 1.5}
]
return(
<main>
<Grid container justify='center' spacing={1}>
{products.map((product) => {
<Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
<Product product={product}/>
</Grid>
})}
</Grid>
</main>
)
}
export default Products
我正在尝试解构 product,jsx 文件中的 product 数组并调用 product.name 但这显示为类型错误
as TypeError: Cannot read property 'name' of undefined react
import React from 'react'
import {Card, CardMedia, CardContent, CardActions, Typography, IconButton, Icon} from '@material-ui/core';
import {AddShoppingCart} from '@material-ui/icons'
import useStyles from './styles';
const Product = ({product}) => {
const classes = useStyles()
return (
<div>
<Card className={classes.root}>
<CardMedia className={classes.media} image='' title={product.name}/>
<CardContent>
<div className={classes.CardContent}>
<Typography variant='h5 gutterbottom'>
{product.price}
</Typography>
<Typography variant='h5'>
{product.name}
</Typography>
</div>
<Typography variant='h2' color='textSecondary'>{product.description}</Typography>
</CardContent>
<CardActions disableSpacing className={classes.CardActions}>
<IconButton aria-label='Add to Cart'>
<AddShoppingCart/>
</IconButton>
</CardActions>
</Card>
</div>
)
}
export default Product
答案 0 :(得分:0)
试着像这样解构。
[...products].map((product) => {
<Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
<Product product={product}/>
</Gri
答案 1 :(得分:0)
返回时不应使用多行: 您可以通过两种方式执行此操作:
{products.map((product) => {
return <Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
<Product product={product}/>
</Grid>
})}
或
{products.map((product) => <Grid item key={product.id} xs={12} sm={6} md={4} lg={3}>
<Product product={product}/>
</Grid>
)}