TypeError: Cannot read properties of undefined (reading 'requestContent')

TypeError: Cannot read properties of undefined (reading 'requestContent')

我在我的 React 应用程序中遇到了这个问题。

TypeError: 无法读取未定义的属性(读取 'requestContent')

我在我的应用程序中使用 commercejs。代码指向 isEmpty=!cart.line_items.length;。检查时,它显示正确的值。此外,我注意到 Api returns NULL 数组两次,第三次填充数组。为什么会这样?有人可以帮我解决这个问题吗?

Cart.jsx

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

import useStyles from "./CartStyles";

const Cart = ({ cart }) => {
  const classes = useStyles();
  console.log("CART ",cart.line_items); 
  const isEmpty = !cart.line_items.length;

  const EmptyCart = () => {
    <Typography variant="subtitle1">
      You donot have any item in your shopping cart. Start adding some of the
      items in your shopping cart.
    </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>
        ))}
        <div className={classes.cartDetails}>
          <Typography variant="h4">
            Subtotal: {cart.subtotal.formatted_With_symbol}
            <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>
          </Typography>
        </div>
      </Grid>
    </>;
  };

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

export default Cart;

App.js

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

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

    const fetchProducts = async() => {
        // call the product api from commerce js
        const { data } = await commerce.products.list();
        // populates the products
        setProducts(data);
    }

    //get element of cart
    const fetchCart = async() => {
        const cartItems = await commerce.cart.retrieve();
        setCart(cartItems);
    }


    const handleAddToCart = async(productId, quantity) => {
        const itemsInCart = await commerce.cart.add(productId, quantity);
        setCart(itemsInCart.cart);
    }

    useEffect(() => {
        //Calling of methods which we want to call on load of component
        fetchProducts();
        fetchCart();
    }, []);
    //  empty array is given so that it makes a call as soon as component is loaded.
    console.log(cart);
    return ( <
        div >
        <
        Navbar totalItems = { cart.total_items }
        / >   <
        Cart cart = { cart }
        /> < /
        div >
    );
};

export default App;

错误截图

问题

此问题是由您在 App 中的初始 cart 状态引起的:

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

它是一个空对象 ({}) 并传递给 Cart 组件,然后假设它有一个 line_items 属性.

const isEmpty = !cart.line_items.length;

由于 cart.line_items 未定义,因此当您尝试引用 length 属性.

时会抛出错误

解决方案

使用可选链接运算符来保护空访问。

const isEmpty = !cart.line_items?.length;

或看守clause/null检查

const isEmpty = !(cart.line_items && cart.line_items.length);

额外

Furthermore, I have noticed that the Api returns NULL array twice and populated array the third time. Why is it so? Anyone there to help me sort this issue?

这可能是函数组件主体中的 console.log("CART ",cart.line_items); 作为无意的副作用和应用被渲染到 React.StrictMode 组件中的组合,该组件有意双重调用某些函数和组件方法两次作为帮助您检测意外副作用的方法。

Detecting unexpected side effects

Strict mode can’t automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions:

  • Class component constructor, render, and shouldComponentUpdate methods
  • Class component static getDerivedStateFromProps method
  • Function component bodies
  • State updater functions (the first argument to setState)
  • Functions passed to useState, useMemo, or useReducer