javascript - ..Use state error: Too many re-renders React 限制渲染次数以防止无限循环
问题描述
好吧,我正在尝试从我的 API 中获取产品并将它们显示在我的“产品”组件中。一切看起来都很好,如果我不尝试增加,我可以访问浏览器上的每个产品,count
但问题是当我尝试count
通过setCount
在我的 JSX 中使用增加时,我收到以下错误Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
我只想count
在循环时将Products
. 例如,如果我得到 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);
在 map 函数内部调用,每次你的组件进入该 map 函数时都会调用它,更新状态,导致无限循环。
您可以像这样在 useEffect 中增加计数:
useEffect(() => {
setCount(count+1);
const myCallBack = (response, status) => {
if (status === 200) {
console.log("products resnpose:", response);
setProducts(response);
}
};
getProducts(myCallBack);
});
推荐阅读
- angular - 使用 ngx-extractor 更新提取的翻译文件
- logback - Logback:我可以更改日志级别名称吗?(警告->警告)
- ios - 如何在 iOS 中为任何定向视频添加水印?
- angular - 角关闭浏览器
- angular - 'array-contains' 查询不适用于引用的 Firestore
- c++ - std::find 的奇怪行为,当元素不在向量中时返回 true
- angular - Angular:检查 json 属性
- windows - 调试 PE 时执行的字节数
- java - 指定 ZonedDateTime 的时区而不更改实际日期
- ios - Swift - 正则表达式提取价值