gpt4 book ai didi

reactjs - React Hook useState 不更新 UI

转载 作者:行者123 更新时间:2023-12-02 14:08:32 25 4
gpt4 key购买 nike

我是 React Hooks 新手,我正在尝试使用以下代码更新购物车中的数量;

import React, { useState, useEffect } from "react";
import cookie from "react-cookies";
import CheckoutItems from "./CheckoutItems";
import restHelper from "../../shared/RestHelper";

const Checkout = () => {
const [cart, setCart] = useState(null);

useEffect(() => {
const cartId = cookie.load("RbCartId");

if (cartId){
(async () => {
const cart = await restHelper.getUserCart(cartId);
setCart(cart);
})();
}
}, []);

const handleQtyUpdate = (evt, id) => {
let _cart = cart;
let items = _cart.cartItems.filter(x => x.id === id);
let cartItem = { ...items[0] };
cartItem.quantity = Number(evt.target.value);
const index = _cart.cartItems.findIndex(x => x.id === cartItem.id);
_cart.cartItems[index] = cartItem;
setCart(_cart);
};

return (
<section>
<div className="container" style={{ marginTop: "80px" }}>
<h3 className="rb-highlight">Shopping Cart</h3>
<table className="table" style={{marginTop: "20px"}}>
<thead>
<tr>
<th>Items</th>
<th style={{ textAlign: "right" }}>Price</th>
<th style={{ textAlign: "right" }}>Quantity</th>
<th style={{ textAlign: "right" }}>Total</th>
</tr>
</thead>
<tbody>
<CheckoutItems cart={cart} onQtyUpdate={handleQtyUpdate} />
</tbody>
</table>
</div>
</section>
);
}
export default Checkout;

CheckoutItems 组件是

import React from "react";

function CheckoutItems({cart, onQtyUpdate}){
if (!cart || cart.cartItems === 0){
return <tr><td colSpan="4"><span className="rb-highlight">There are no items in your cart</span></td></tr>;
}
else{
const cartItems = cart.cartItems.map((item, index) => {
return <tr key={index}>
<td>{item.description}</td>
<td style={{textAlign: "right"}}>&euro;{item.cost}</td>
<td style={{textAlign: "right"}}><input type="text" id={item.id} name="quantity" value={item.quantity} onChange={(evt) => onQtyUpdate(evt, item.id)} /></td>
<td style={{textAlign: "right"}}>&euro;{item.cost * item.quantity}</td>
</tr>
})
return cartItems;
}
}

export default CheckoutItems;

购物车商品已在 handleQtyUpdate 中成功更新,但 UI 中的值未更新。根据我所读到的内容,我应该使用 useEffect 来更新购物车,但我不确定如何从 handleQtyUpdate 中使用它。

最佳答案

问题是状态比较很浅,这意味着,在对象的情况下,只会比较引用。

在您的示例中,您更新了 cartItems 属性,但没有更新对象实例,因此就 React 而言,状态并未更改,因为它不会检查单个属性。

尝试每次创建一个全新的购物车,您应该会看到 UI 更新,例如

 setCart({ ..._cart })

关于reactjs - React Hook useState 不更新 UI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59690934/

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