gpt4 book ai didi

javascript - 类型错误 : Cannot read properties of undefined (reading 'requestContent' )

转载 作者:行者123 更新时间:2023-12-05 03:37:28 28 4
gpt4 key购买 nike

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

类型错误:无法读取未定义的属性(读取“requestContent”)

我在我的应用程序中使用 commercejs。代码指向 isEmpty=!cart.line_items.length;。检查时,它显示正确的值。此外,我注意到 Api 两次返回 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;

错误截图 enter image description here

最佳答案

问题

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

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

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

const isEmpty = !cart.line_items.length;

cart.line_items未定义当您尝试引用 length 时会抛出错误属性(property)。

解决方案

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

const isEmpty = !cart.line_items?.length;

或者保护子句/空检查

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

附加

Furthermore, I have noticed that the Api returns NULL array twice andpopulated array the third time. Why is it so? Anyone there to help mesort 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 itcan 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

关于javascript - 类型错误 : Cannot read properties of undefined (reading 'requestContent' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69294482/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com