【发布时间】:2022-01-08 02:21:29
【问题描述】:
我要编辑的对象以 JSON 格式进行编辑,但只有以前的数据会显示在浏览器中。我使用这些钩子从本地存储中获取产品列表
const Cart = () => {
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(()=>{
setProducts(loadCart());
setLoading(false)
},[])
然后我映射所有对象
const mapProducts = (products) => {
return (
<>
{products.map((product) => {
return (
<>
<div className="cart-detail">
<h4>{product.name} - {product.price}$
/ total: {product.price * product.amount}$</h4>
<h4>{product.amount}</h4>
<button onClick={() => incrementAmount(product)}>+</button>
</div>
</>
)
})}
</>
)
}
return (
<Base title="Cart">
{loading && <h1>Loading...</h1>}
{!loading && mapProducts(products)}
</Base>
)
incrementAmount() 函数如下所示:
const incrementAmount = (product) => {
let tempList = products
for (let i = 0; i < tempList.length; i++) {
if (tempList[i].id === product.id) {
tempList[i].amount++;
}
}
setProducts(tempList)
}
从我在控制台中看到的情况来看,数组看起来不错,并且我要编辑的对象已被编辑。 FE:我有一个对象 {name:"hoodie", amount:3} 在单击“+”按钮后它会正确更改为 {name:"hoodie", amount:4}(在 products 和 tempList 中)但是仅在控制台中,在文档中它仍将 product.amount 显示为 3,我不知道为什么
【问题讨论】:
-
您需要创建一个新的数组实例
let tempList = [...products]并使用它来设置新状态。
标签: javascript reactjs react-hooks use-effect use-state