React 中的 ChartJS 抛出 'too may re-renders'

ChartJS in React throws 'too may re-renders'

我正在尝试使用 ChartJS 创建条形图。当我启动我的应用程序时,网页上没有任何内容,控制台中出现一些错误:'Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.'

我的代码:

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 限制渲染次数以防止无限循环

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

您需要向 useEffect 添加依赖数组。从依赖项数组中排除项可能会导致无限更新链。

添加依赖数组作为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

想要运行只效果一次?

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.

docs

中了解更多信息