【发布时间】:2021-03-18 19:42:51
【问题描述】:
好吧,我正在尝试从我的 API 获取产品并将它们显示在我的“产品”组件中。一切看起来都很好,如果我不尝试增加count,我可以访问浏览器上的每个产品,但问题是当我尝试在我的 JSX 中使用setCount 增加count 时,我收到以下错误Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
我只想在循环通过Products 时将count 加一。例如,如果我得到 3 products,我希望我的 count 是 1,2,然后是 3。
以下代码是我的productscomponent
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;
【问题讨论】:
-
为什么要为
count使用状态变量? return 语句中的setCount导致渲染循环。您到底想通过count状态变量来实现什么?如果您只想渲染第一个product项,可以使用索引作为map函数中的第二个参数。 -
其实没什么。当我通过
map中的每个product时,我只想增加count。 -
你不应该在 JSX 中使用
setCount(count + 1);,在useEffect中使用 -
你能告诉我区别吗?我的意思是当我尝试在 JSX 中使用
useState时,为什么会进入无限循环? -
@AliZiyaÇEVİK 然后呢?也许您可以提供有关您需要计数变量的更多信息?您打算以后使用它吗?
标签: javascript reactjs react-hooks jsx