![](/img/trans.png)
[英]React function Component state - Too many re-renders. React limits the number of renders to prevent an infinite loop
[英]..Use state error: Too many re-renders React limits the number of renders to prevent an infinite loop
好吧,我正在嘗試從我的 API 獲取產品並將它們顯示在我的“產品”組件中。 一切看起來都很好,如果我不嘗試增加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.
當我遍歷Products
時,我只想將count
加一。 例如,如果我有 3 個products
,我希望我的count
是 1,2,然后是 3。
以下代碼是我的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.
您可以像這樣在 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.