开发者问题收集

无法读取购物车组件未定义的属性“长度”

2021-06-08
314

我正在构建一个购物车组件并尝试格式化购物车布局。我只想查看购物车的布局,所以我注释掉了产品组件,该组件应该可以单独获取购物车布局,这样我就可以看到它的外观和正在发生的事情,但是当我尝试在 React 中编译它时,我不断收到以下错误:“TypeError:无法读取未定义的属性‘length’”。

我的购物车组件代码:

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

const Cart = ({ cart }) => {
  const isEmpty = !cart.line_items.length;
  const classes = useStyles();
  const EmptyCart = () => (
    <Typography variant="subtitle1">No items selected</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.checkoutButton}
            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;

错误具体位于以下行:

const isEmpty = !cart.line_items.length;

还有我的 App JS 代码:

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

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();
  }, []);

  console.log(cart);

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

export default App;

任何帮助都非常感谢。

1个回答

问题

初始渲染时没有 cart.line_items ,因为初始状态是一个空对象 ( { )。

const [cart, setCart] = useState({});

解决方案

为初始渲染提供有效的初始状态,以便有一个真实的、定义的 cart.line_items 对象,从中可以得到 length 属性,也就是说, !cart.line_items.length; 可以解析为一个值,而不会引发错误。

const [cart, setCart] = useState({ line_items: [] });
Drew Reese
2021-06-08