Highcharts React饼图多次呈现

chy5wohz  于 2022-11-10  发布在  Highcharts
关注(0)|答案(1)|浏览(191)

我的代码是

import React, { useEffect, useRef, useState } from "react";
import * as Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";

export const PieChart = (props: any) => {
  const [chartIsLoaded, setChartIsLoaded] = useState(false);
  const series: any = [{
    innerSize: '80%',
    name: props.name,
    colorByPoint: true,
    data: props.chartData
  }]
  useEffect(() => {
    setChartIsLoaded(true);
  }, [])

  const chartComponentRef = useRef<HighchartsReact.RefObject>(null);
  const options: Highcharts.Options = {
    chart: {
        backgroundColor: "#0c0c0c",
        borderColor: "#0c0c0c",
        plotBorderWidth: 0,
        plotShadow: false,
        type: 'pie',
        height: "70%",
    },
    title: {
        style : {
            display : 'none'
          }
    },
    tooltip: {
      pointFormat: '<b>{point.percentage:.1f}%</b>',
      backgroundColor: "#1B1B1B",
      borderColor: "transparent",
      valueDecimals: 2,
      borderRadius: 0,
      style: {
        color: "#fff",
        fontSize: "15px"

      }
    },
    accessibility: {
        point: {
            valueSuffix: '%'
        }
    },
    legend: {
        itemStyle: {color: "#fff", fontWeight: "400", fontFamily: "teragon-sans"}
    },
    plotOptions: {
        pie: {
            borderColor: "#0c0c0c",
            borderWidth: 6,
            allowPointSelect: true,
            color: "#fff",
            cursor: 'pointer',
            dataLabels: {
                enabled: false,
            },
            showInLegend: true
        }
    },
    series: series
  };
  return (
    <div>
      {chartIsLoaded &&
        <HighchartsReact
          highcharts={Highcharts}
          options={options}
          ref={chartComponentRef}
          oneToOne={true}
        />
      }
    </div>
  );
};

chartData来自此代码:

let data = sheetData[0].data;
let invesment = await groupData(data, "Investment Type");

问题:图表渲染多次。而且,我有条形图,它发生在那。没有问题的折线图。数据正在准备与减少功能,但它的异步等待等待。此外,我尝试与承诺。不幸的是,它再次渲染多次。我该如何修复这种情况?

dsekswqp

dsekswqp1#

您的图表选项会在每次组件更新后启动,它会在每次组件更新时指向图表更新。我建议您将图表选项放在一个显眼的位置或记住它们。例如:

const PieChart = ({ name, chartData }) => {
  const [chartOptions, setChartOptions] = useState(false);

  useEffect(() => {
    const series = [
      {
        innerSize: "80%",
        name,
        colorByPoint: true,
        data: chartData
      }
    ];
    const options = {
      ...,
      series
    };

    if (chartData) {
      setChartOptions(options);
    }
  }, [chartData]);

  return (
    <div>
      {chartOptions && (
        <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      )}
    </div>
  );
};

现场演示:https://codesandbox.io/s/highcharts-react-demo-fz6rr6?file=/demo.jsx
**文档:**www.npmjs.com/package/highcharts-react-official#optimal-way-to-update

相关问题