代码之家  ›  专栏  ›  技术社区  ›  Jugennd

React中的ChartJS抛出“太可能重新渲染”

  •  0
  • Jugennd  · 技术社区  · 3 年前

    我正在尝试使用ChartJS创建条形图。当我启动我的应用程序时,网页上并没有任何内容,控制台中也有一些错误:“未捕获错误:重新渲染太多。”。React限制渲染的数量,以防止无限循环。”

    我的代码:

    import {
      Chart as ChartJS,
      CategoryScale,
      LinearScale,
      BarElement,
      Title,
      Tooltip,
      Legend
    } from 'chart.js'
    import {Bar} from 'react-chartjs-2'
    import React, {useState, useEffect} from 'react'
    
    ChartJS.register(
      CategoryScale,
      LinearScale,
      BarElement,
      Title,
      Tooltip,
      Legend
    );
    
    function App() {
    
      const [chartData, setChartData] = useState({
        datasets:[],
      })
    
      const [chartOptions, setChartOptions] = useState({});
    
      useEffect(()=>{
        setChartData({
          labels: ['john','kevin','george','mike','oreo'],
          datasets:[
            {
              label: 'label',
              data: [12,55,34,120,720],
              borderColor: 'green',
              backgroundColor: 'blue',
            },
          ],
        })
      },[])
      setChartOptions({
        responsive:true,
        plugins:{
          legend:{
            position:'top'
          },
          title:{
            display:true,
            text:'text from tittle'
          }
        }
      })
    
    
      return (
        <div className="App">
          <Bar options={chartOptions} data={chartData}/>
        </div>
      );
    }
    

    错误:重新渲染过多。React限制渲染的数量以防止无限循环

    我应该怎么做才能在网页上看到图表?

    1 回复  |  直到 3 年前
        1
  •  1
  •   pez    3 年前

    您需要将依赖项数组添加到 useEffect . 从依赖关系数组中排除项目可能会导致无限的更新链。

    添加依赖项数组作为的第二个参数 使用效果 :

      useEffect(()=>{
        setChartData({
          labels: ['john','kevin','george','mike','oreo'],
          datasets:[
            {
              label: 'label',
              data: [12,55,34,120,720],
              borderColor: 'green',
              backgroundColor: 'blue',
            },
          ],
        })
      },[])
      setChartOptions({
        responsive:true,
        plugins:{
          legend:{
            position:'top'
          },
          title:{
            display:true,
            text:'text from tittle'
          }
        }
      }, [chartOptions, chartData]) // effect will run when either changes
    

    只想运行一次效果?

    如果您想运行一个效果并只清理一次(在装载和 unmount),可以将空数组([])作为第二个参数传递。这 告诉React您的效果不依赖于道具的任何值 或状态,因此它永远不需要重新运行。这不是作为特殊的 案例–它直接从依赖项数组总是 作品

    在中了解更多信息 docs

    推荐文章