UseEffect在从数组中删除数据时不渲染,只有在添加数据时才渲染


import React, { useEffect, useState } from 'react'
import { HiOutlineBackspace } from "react-icons/hi";
import {MdOutlineCancel} from 'react-icons/md'
const Cart = ({toggleCart}) => {
const localStorageCart = JSON.parse(localStorage.getItem('MY_CART')) || []
const [cartItem, setCartItem] = useState(localStorageCart)
*************************************  
const handleDeleteButton = (index) => {
cartItem.filter(cartItem[index])
console.log(cartItem);
}
**************************************
useEffect(() =>{
setCartItem(cartItem)
},[cartItem])
return (
<div className='cartContainer'>
<h1 style={{textAlign:"center"}}>Your Cart</h1>     
<button 
style={{backgroundColor:'transparent'}}
onClick={toggleCart}
>
<HiOutlineBackspace/>
</button>
<div className='cartCardContainer'>  
{cartItem.map((cartItem,index) =>{
return(
<div className="cartCard" key={index}>
<img src={cartItem.img} alt="logo" id="img" />
<h2>{cartItem.title}</h2>
<div className="description">
<h5>{cartItem.description}</h5>
</div>
<div className="priceCard"  >
<h3>${cartItem.price}</h3>
</div>
<button onClick={() => handleDeleteButton(index)}>***********************
<MdOutlineCancel/>
</button>
</div>
)
})}

</div>
</div>
)
}
export default Cart

我正在研究一个电子商务添加到购物车功能。

通过使用useEffect,我成功地在添加项目时渲染了购物车,因为它是一个单页应用程序。

但是当我试图拼接()cartItem时,我听说这不是一个好的做法,我应该使用filter()代替,但我有麻烦这样做,因为我已经尝试了很多方法,过滤器不按计划进行,或者它只是不运行。

对于项目的这一部分,我使用了很多本地存储,因为它是addToCart组件

我把*符号在我认为可能有问题的地方

过滤未正确实现。此外,您必须在从状态中过滤/删除项后更新状态。

可以使用splice()从数组中删除一个元素。

handleDeleteButton应该是这样的:

const handleDeleteButton = (index) => {
cartItem.splice(index, 1)); // 1 means remove one item only
setCartItem([...cartItem]);
}

filter方法根据您提供的条件返回一个新的数组。所以在你的代码中,你实际上并没有改变cartItem的状态。

过滤你的cartItem数组并使用返回值来设置你的cartItem状态。

const handleDeleteButton = (index) => {
setCartItem(cartItem.filter(...));
}

作为旁注,您最好使用与项相关的键或标识符来过滤项,而不是使用map函数的索引值。

useEffect在你更新状态时醒来,你的状态现在是cartItem,要更新此状态,最重要的是在函数中很好地执行setCartItem,您必须这样做:

setCartItem(cartItem.splice(cartItem[index],1)

我不知道你的数组cartItem里面有什么,你可以用setCartItem过滤并改变它