[英]..Use state error: Too many re-renders React limits the number of renders to prevent an infinite loop
Well, I'm trying to get products from my API and display them in my 'Products' component.好吧,我正在尝试从我的 API 获取产品并将它们显示在我的“产品”组件中。 Everything looks fine and I can reach every single product on my browser if I just don't try to increment
count
but the problem is when I try to increment count
by using setCount
in my JSX I get this following error Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
一切看起来都很好,如果我不尝试增加
count
,我可以访问浏览器上的每个产品,但问题是当我尝试在 JSX 中使用setCount
增加count
时,我收到以下错误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.
I just want to increment the count
by one when I loop through Products
.当我遍历
Products
时,我只想将count
加一。 For example, If I got 3 products
I want my count
to be 1,2 then 3.例如,如果我有 3 个
products
,我希望我的count
是 1,2,然后是 3。
This following code is my products
component以下代码是我的
products
组件
import React, { useEffect, useState } from "react";
import { getProductKinds, getProducts } from "../lookup";
function Products() {
const [count, setCount] = useState(0);
const [products, setProducts] = useState([]);
useEffect(() => {
const myCallBack = (response, status) => {
if (status === 200) {
console.log("products resnpose:", response);
setProducts(response);
}
};
getProducts(myCallBack);
}, []);
return (
<div>
{products.map((product) => {
console.log(count);
setCount(count + 1);
if (count === 0) {
return (
<div className="card-group container">
<div className="card shadow" style={{ width: "18rem" }}>
<img
className="card-img-top"
src="https://dl.airtable.com/.attachmentThumbnails/65708b701baa3a84883ad48301624b44/2de058af"
alt="Card image cap"
/>
<div className="card-body">
<p className="card-text">
Some quick example text to build on the card title and make
up the bulk of the card's content.
</p>
</div>
</div>
</div>
);
}
})}
</div>
);
}
export default Products;
setCount(count + 1);
is called inside the map function and every time your component goes into that map function this is called, updating the state, resulting in an infinite loop. is called inside the map function and every time your component goes into that map function this is called, updating the state, resulting in an infinite loop.
You can increment count inside useEffect like this:您可以像这样在 useEffect 中增加计数:
useEffect(() => {
setCount(count+1);
const myCallBack = (response, status) => {
if (status === 200) {
console.log("products resnpose:", response);
setProducts(response);
}
};
getProducts(myCallBack);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.