gpt4 book ai didi

reactjs - 太多的重新渲染。 React 限制渲染次数以防止无限循环。在 render 方法中更新功能组件的状态

转载 作者:行者123 更新时间:2023-12-04 00:59:27 25 4
gpt4 key购买 nike

每次显示购物车商品时,我都想使用 render 方法中的 useState 函数更新商品的总价和数量。但是,在呈现 UI 后,我立即收到上述 react 错误。

有没有更好的方法来完成我想要实现的目标而不会出现错误?

const Cart = () => {
const cartItems = useItems()
const firebase = useFirebase()
//Items count

//Total amount of the items
let [total, updateTotal] = useState(0)
let [count, updateCount] = useState(1)

//Method to add items to the cart
useEffect(() => {
if (!firebase) return
}, [firebase, cartItems])




return (
<Layout>
<SEO title="Cart" />
<Navbar count={count} />
<MDBContainer>
<MDBCol lg="12" className="">
<MDBTable responsive className="mt-5 z-depth-1">
<MDBTableHead>
<tr className="bg-light">
<th>
<div className="p-1 px-3 text-uppercase font-weight-bold">
Product
</div>
</th>
<th>
<div className="p-1 px-3 text-uppercase font-weight-bold">
Price
</div>
</th>
<th>
<div className="p-1 px-3 text-uppercase font-weight-bold">
Quantity
</div>
</th>
<th>
<div className="p-1 px-3 text-uppercase font-weight-bold">
Remove
</div>
</th>
</tr>
</MDBTableHead>
<MDBTableBody id="products-list">
{cartItems.map(product => {
updateTotal((total += product.price))
updateCount((count += 1))
return (
<tr>
<td class="px-3 font-weight-normal">
{product.name} <span class="d-none">{product.id}</span>{" "}
</td>
<td width="10%" class="text-center font-weight-normal">
{product.price}
<span>/kg </span>{" "}
</td>
<td width="10%" class="text-center font-weight-normal">
{product.count}
</td>
<td width="10%" class="text-center">
<div class="px-3 font-weight-normal">
{" "}
<button
class="bg-transparent border-0"
id="delete-button"
>
<i class="fa fa-trash-alt delete-icon"></i>
</button>
</div>
</td>
</tr>
)
})}
</MDBTableBody>
<MDBTableFoot>
<tr>
<td className="px-3 text-uppercase font-weight-bold">Total</td>
<td className="font-weight-bold px-5">&#8377;{total}</td>
<td className="font-weight-bold pr-2 text-center">{count}</td>
</tr>
</MDBTableFoot>
</MDBTable>
</MDBCol>
</MDBContainer>
</Layout>
)
}

export default Cart

最佳答案

使用空白 [] 而不是 [firebase, cartItems]

关于reactjs - 太多的重新渲染。 React 限制渲染次数以防止无限循环。在 render 方法中更新功能组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59798250/

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