开发者问题收集

TypeError:访问购物车时无法读取 Commerce JS 中未定义的属性“length”

2020-12-23
1692

当访问 commerce js 中 cart 对象的 line_items 数组时,出现错误,提示未定义,但我仍然可以在控制台中看到它。

以下是一些截图:

错误:

TypeError: Cannot read property 'length' of undefined
Cart
D:/Zayeed/Projects/e_commerce/src/components/Cart/Cart.jsx:7
   4 | 
   5 | const Cart = ({ cart }) => {
   6 |     const classes = useStyles();
>  7 |     const isEmpty = !cart.line_items.length;
   8 | 
   9 |     const EmptyCart = () => (
  10 |         <Typography variant="subtitle1">You have no items in your cart, start adding some.</Typography

我的代码:

import React from 'react'
import { Container, Typography, Button, Grid } from '@material-ui/core'
import useStyles from './styles';

const Cart = ({ cart }) => {
    const classes = useStyles();
    const isEmpty = !cart.line_items.length;

    const EmptyCart = () => (
        <Typography variant="subtitle1">You have no items in your cart, start adding some.</Typography>
    );

    const FilledCart = () => {
        <>
            <Grid container spacing={3}>
                {cart.line_items.map(item => (
                    <Grid item xs={12} sm={4} key={item.id}>
                        <div>{item.name}</div>
                    </Grid>
                ))}
            </Grid>

            <div className={classes.cardDetails}>
                    <Typography variant="h4">Subtotal: {cart.subtotal.formatted_with_symbol}</Typography>
                    <div>
                        <Button className={classes.emptyButton} size="large" type="button" variant="contained" color="secondary">Empty Cart</Button>
                        <Button className={classes.checkout} size="large" type="button" variant="contained" color="primary">Checkout</Button>
                    </div>
            </div>
        </>
    }

    return (
        <Container>
            <div className={classes.toolbar}/>
            <Typography className={classes.title} variant="h3">Your Shopping Cart:</Typography>
            {isEmpty ? <EmptyCart/> : <FilledCart />}
        </Container>
    )
}

export default Cart

cart 对象的控制台日志:

App.js:

import React, { useState, useEffect } from 'react'
import { commerce } from './lib/commerce'
import { Products, Navbar, Cart } from './components'

const App = () => {
    const [ products, setProducts ] = useState([])
    const [cart, setCart] = useState({})

    const fetchProducts = 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(() => {
        fetchProducts()
        fetchCart()
    }, []);

    return (
        <div>
            <Navbar  totalItems={cart.total_items}/>
            {/* <Products products={products} onAddToCart={handleAddToCart}/> */}
            <Cart cart={cart}/>
        </div>
    )   
}

export default App

似乎 prop 没有按预期导入,我无法访问 cart 对象的任何属性。

提前致谢!

3个回答

发生这种情况的原因是页面打开时购物车内容没有立即从电子商务 API 加载,然后由于错误它就卡住了。

您可以先检查是否有购物车内容,然后删除 isEmpty 变量并只在 javascript 闭包中写入,在视频中几秒钟后进行了解释,但经过一天的努力,我也意识到了这一点:D

if(!cart.line_items)
    return  '...loading';


return (
    <div className={classes.toolbar}>
        <Typography className={classes.title} variant="h3"> Your Shopping Cart 
        </Typography>
        {!cart.line_items.length ? <EmptyCart /> : <FilledCart />}
       
    </div>
)
abdullah yıldız
2021-04-29

尝试 const isEmpty = Object.keys(cart).length && !cart.line_items.length; 未从服务器接收数据,但组件已呈现,这就是为什么最初 card 未定义的原因。

leonae
2020-12-23

尝试使用可选链:

const isEmpty = !cart.line_items?.length

仅当数组存在时,此方法才会询问数组长度,从而防止出现未定义错误。 这意味着,如果 cart.line_items == undefinedcart.line_items.length == 0 ,它将返回 false。

也许我有点迟到了,但我被困在了同一个部分,这解决了我的问题(而且我认为它看起来非常整洁)

Guido Queiroz
2021-11-17