[英]Error: Too many re-renders. React limits the number of renders to prevent an infinite loop. - React JS
So my application was working fine until I tried to add "add to cart" functionality.所以我的应用程序运行良好,直到我尝试添加“添加到购物车”功能。 I am trying to fetch products from backend API and display it into my app (which worked fine previously) and add to cart functionality where users can click add to cart and it adds the specific product into their localstorage but I get
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
我正在尝试从后端 API 获取产品并将其显示到我的应用程序中(以前运行良好)并添加到购物车功能,用户可以单击添加到购物车并将特定产品添加到他们的本地存储中,但我得到
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
error when I simply load up the page.当我只是加载页面时出错。 Here is my code:
这是我的代码:
import React, {useState, useEffect} from 'react'
import { Card, Button } from 'react-bootstrap'
import axios from 'axios'
function HomeScreen() {
const [products, setProducts] = useState([])
const [cart, setCart] = useState([])
function handleClick(product) {
setCart(cart + product)
localStorage.setItem("cartItems", cart)
}
useEffect(() => {
async function getProducts() {
try {
const response = await axios.get('http://localhost:8000/api/products/');
setProducts(response.data);
} catch (error) {
console.error(error);
}
}
getProducts()
},[])
return (
<div>
{products.map(product => (
<Card className="my-3 p-3 rounded" key={product.id}>
<Card.Img src={'http://localhost:8000' + product.image} />
<Card.Body>
<Card.Title as="div">
<strong>{product.name}</strong>
</Card.Title>
<Card.Text as="div">
</Card.Text>
<Card.Text as="h3">
${product.price}
</Card.Text>
<Card.Link>
<Button onClick={handleClick(product)} className="btn-primary">Add to cart</Button>
</Card.Link>
</Card.Body>
</Card>
))}
</div>
)
}
export default HomeScreen
onClick={()=>handleClick(product)}
Passing the handleClick function to onClick actually runs it causing a re-render everytime the Button is rendered.将 handleClick function 传递给 onClick 实际上会运行它,导致每次呈现 Button 时都会重新渲染。
Passing it as a arrow function, passes the function object without executing it, until the onClick method is called.将其作为箭头传递 function,传递 function object 而不执行它,直到调用 ZB73CAB20CE55AD048CA36 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.