简体   繁体   English

为什么我的组件会抛出“太多重新渲染”错误?

[英]Why is my component throwing a "too many re-renders" error?

Error: Too many re-renders.错误:重新渲染过多。 React limits the number of renders to prevent an infinite loop. React 限制了渲染的数量以防止无限循环。

I couldn't find where the loop is, I managed to check if the states are different from "null" I could only render the graph and avoid the error, but it persists, could someone help me?..我找不到循环在哪里,我设法检查状态是否不同于“null”我只能渲染图表并避免错误,但它仍然存在,有人可以帮助我吗?

import React from "react";
import { useState } from "react";
import { Chart } from "react-google-charts";

export const StatusChart = (pokemon) => {
  const [hp, setHp] = useState(null);
  const [attack, setAttack] = useState(null);
  const [defense, setDefense] = useState(null);
  const [specialAtack, setSpecialAtack] = useState(null);
  const [specialDefese, setSpecialDefese] = useState(null);
  const [speed, setSpeed] = useState(null);

  console.log(
    pokemon.pokemon.map((e) => {
      console.log(e.base_stat);
      switch (e.stat.name) {
        case "hp":
          setHp(e.base_stat);
          break;
        case "attack":
          setAttack(e.base_stat);
          break;
        case "defense":
          setDefense(e.base_stat);
          break;
        case "special-attack":
          setSpecialAtack(e.base_stat);
          break;
        case "special-defense":
          setSpecialDefese(e.base_stat);
          break;
        case "speed":
          setSpeed(e.base_stat);
          break;
      }
    })
  );

  const data = [
    ["Status", "Value", { role: "style" }],
    ["HP", hp, "red"],
    ["Atack", attack, "orange"],
    ["Defese", defense, "green"],
    ["Special Atack", specialAtack, "gold"],
    ["Special Defense", specialDefese, "purple"],
    ["Speed", speed, "blue"],
  ];

  return (
    <>
      {hp ||
      attack ||
      defense ||
      specialAtack ||
      specialDefese ||
      speed === null ? null : (
        <Chart
          chartType="ColumnChart"
          width="100%"
          height="300px"
          data={data}
        />
      )}
    </>
  );
};

Github link: https://github.com/yjdutra/pokedex-pokeapi Github 链接: https://github.com/yjdutra/pokedex-pokeapi

This console.log with a map inside is doing many setStates at the same time, causing the UI to re-render at each "pokemon" entity that you have.这个带有 map 的 console.log 同时执行许多 setState,导致 UI 在您拥有的每个“口袋妖怪”实体上重新渲染。 This is causing the error.这导致了错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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