【发布时间】:2021-09-23 05:31:32
【问题描述】:
我在我的 react 应用程序中遇到了这个问题。
TypeError:无法读取未定义的属性(正在读取“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;
【问题讨论】:
标签: javascript reactjs commerce