类型错误: 无法读取未定义的购物车的属性'map'



我有两个组件App.js和Cart.js我正在为这个应用程序使用material ui和commerce.js apiApp.js:

import React , {useState , useEffect} from 'react'
import Products from './Components/Products/Products'
import Navbar from './Components/NavBar/Navbar'
import {commerce} from './assests/lib/Commerce'
import Cart from './Components/Cart/Cart'
export default function App(props) {
const [products , setproducts] = useState([])
const [cart , setCart] = useState([])
const fetchData = async ()=>{
const {data } = await commerce.products.list()
setproducts(data)
}
const fetchCart = async ()=>{
setCart(await  commerce.cart.retrieve())   
}

const handleAddtoCart = async (productId , quantity)=>{
const item = await commerce.cart.add(productId , quantity)
setCart(item.cart)
}

useEffect(()=>{
fetchData()
fetchCart()
},[])
console.log(products)
console.log(cart)
return (
<>

< Navbar totalItems={cart.total_items}/>
<Cart cart={cart}/>
</>
)
}

Cart.js:

import React from 'react'
import {Container ,  Grid , Button , Typography} from '@material-ui/core'
import useStyles from './styles'
//import cart from '../../App'
const Cart = ({cart}) => {

console.log(cart)


const classes = useStyles();

const isEmpty = cart.length
const EmptyCart = ()=>{
<Typography variant='2' >Your Cart is Empty</Typography>
}
const FilledCart = (cart) =>{
<>
<Grid Container spacing={3} >
{cart.line_items.map((cartitem)=>
(
<Grid item xs={12} sm={4} key={cartitem.id}>
{cartitem.name}
</Grid>
))}
</Grid>
<div className={classes.cardDetails}>
<Typography variant='h4'>
SubTotal : {Cart.subtotal.formated_with_symbol}
</Typography>
</div>
<div>
<Button className={classes.emptyButton} size='large' type='button' variant='contained' color='secondary'>
Empty Cart
</Button>
<Button className={classes.checkoutButton} size='large' type='button' variant='contained' color='primary'>
Check out Cart
</Button>
</div>
</>
}
return (
<Container>
<div className={classes.toolbar}/>
<Typography variant="3" className={classes.title}>
Your Shopping Cart
</Typography>
{ isEmpty ? <EmptyCart /> : <FilledCart /> }
</Container>
)
}
export default Cart

当我试着运行它时,它会说";无法读取未定义的属性,cart">

第一次渲染时,cart.length为0。所以isEmpty的值为0,这是一个错误的值。因此,将渲染FilledCart而不是EmptyCart

由于它是一个空数组,cart.lineitems将未定义。这里是错误cannot do map on undefined

所以你需要将你的代码更改为

const isEmpty = cart.length === 0

相关内容

  • 没有找到相关文章

最新更新