首页 > 解决方案 > ..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;

标签: javascriptreactjsreact-hooksjsx

解决方案


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);
  });

推荐阅读