简体   繁体   中英

..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. 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. 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 . For example, If I got 3 products I want my count to be 1,2 then 3.

This following code is my products component

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.

You can increment count inside useEffect like this:

useEffect(() => {
    setCount(count+1);
    const myCallBack = (response, status) => {
      if (status === 200) {
        console.log("products resnpose:", response);
        setProducts(response);
      }
    };
    getProducts(myCallBack);
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM