当我试图在Reaction应用程序中更新状态时,我的结果是不确定.我基本上是在try 从List组件中删除一项,并try 通过获取先前的状态来更新状态.但当我试图删除该项目时,我的定义变得不明确.
现在,我有这个代码:
const Checkout = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
const [finalPrice, setFinalPrice] = useState(0);
const { basketItems, setBasketItems } = useContext(ProductTypeContext);
useEffect(() => {
basketItems &&
basketItems.forEach((id) => {
axios
.get(`http://localhost:6969/api/products/${id}`)
.then((data) => {
setProducts((prevState) => [...prevState, data.data.product]);
setFinalPrice((prevState) => Number(prevState) + Number(data.data.product.price));
setTimeout(() => {
setLoading(false);
}, 300);
})
.catch((err) => console.log(err));
});
}, []);
if (loading) {
return <div>Loading...</div>;
}
return (
<>
<div className="checkout-container">
{products.map((product, index) => (
<div key={index} className="checkout-products">
<img src={product.img} width="100px" />
<div>{product.name}</div>
<div>{product.price}</div>
<div>{product.taste}</div>
<span
onClick={() => {
setBasketItems((prevState) => {
[...prevState, prevState.splice(index, 1)];
});
}}
>
X
</span>
</div>
))}
</div>
<div>Final Price: {finalPrice}</div>
</>
);
};
export default Checkout;
我想当我点击X按钮时,有些地方出了问题,那就是更新状态.有什么建议吗?