我有一个Cart组件,里面有一系列Cards。
每次用户从购物车中删除产品时,我都会从本地存储中删除产品,
并将其从用户界面中删除。
import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import Layout from '../Layout';
import Card from '../Home/Card';
import { getCart } from './cartHelpers';
const Cart = () => {
const [items, setItems] = useState([]);
useEffect(() => {
setItems(getCart());
}, [items]);
const showItems = () => {
return (
You have {`${items.length}`} items in your cart
{items.map((prod, index) => (
....... />
))}
);
};
const noItemsMsg = () => (
Your cart is empty! Continue Shopping
);
return (
title='Shopping Cart'
desc='Manage your cart items'
className='container-fluid'
>
{items && items.length > 0 ? showItems(items) : noItemsMsg()}
Show Checkout Options / Shipping Address / Total / Update Quantity
);
};
export default Cart;
和Card.js:
import React, { useState } from 'react';
import moment from 'moment';
import { Link, Redirect } from 'react-router-dom';
import ShowImage from '../ShowImage';
import { addItemToCart, updateItem, removeItem } from '../Cart/cartHelpers';
const Card = ({product,
.............
}) => {
const [redirect, setRedirect] = useState(false);
const [countHowManyCopies, setCountHowManyCopies] = useState(product.count);
const showRemoveButton = () => {
return (
showRemoveProductBtn && (
onClick={() => removeItem(product._id)}
className='btn btn-outline-danger mt-2 mb-2'
>
Remove Product
)
)
};
return (
.............. // more code
{showRemoveButton()}
.............. // more code
);
};
export default Card;
每当用户点击“删除项目”按钮,我都会得到:
Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn't have a dependency array, or one of the dependencies changes on every render.
解决此问题的最佳方法是什么?
It happens because of this piece of code (items in the array):
useEffect(() => {
setItems(getCart());
}, [items]);