首页 > 解决方案 > Highcharts 不会在值更改时重新加载或重新渲染图表

问题描述

我在 highcharts 中创建了圆环图,其中数据值在选择下拉列表时发生变化。

代码沙盒代码

从下拉列表中选择时,数据会更改,但图表不会重新呈现,并且更新的数据也不会显示在图表中。任何数据的图表都保持不变。

我尝试包括oneToOne={true}。但这也无济于事。

关于相同的问题有一些类似的问题,但它们对我的情况没有帮助。

如果有人有任何想法或需要任何进一步的信息,请告诉我。

标签: reactjshighchartsreact-hooks

解决方案


一种解决方案是使用useEffect钩子并传入detailsuseEffect 依赖项,因此每次详细信息都会改变他的状态时,useEffect 将被触发并且您的 dataValues 将被更新:

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
// Import Highcharts
import Highcharts from "highcharts/highstock";
import PieChart from "highcharts-react-official";

const App = () => {
  const [details, setDetails] = useState("sup");
  let dataValue = [
    ["Firefox", 45.0],
    ["IE", 26.8],
    ["Chrome", 12.8],
    ["Safari", 8.5],
    ["Opera", 6.2],
    ["Others", 0.7]
  ]; //pass default "sup" to datavalue
  const [chartOptions, setChartOptions] = useState({
    chart: {
      type: "pie"
    },
    title: {
      text: ""
    },
    plotOptions: {
      pie: {
        size: "50%",
        allowPointSelect: true,
        cursor: "pointer",
        depth: 35,
        innerSize: 100,
        dataLabels: {
          enabled: false
        },
        showInLegend: true
      }
    },
    series: [
      {
        type: "pie",
        name: "Browser share",
        data: dataValue
      }
    ]
  });
  useEffect(() => {
    console.log(details);
    if (details === "sup") {
      dataValue = [
        ["Firefox", 45.0],
        ["IE", 26.8],
        ["Chrome", 12.8],
        ["Safari", 8.5],
        ["Opera", 6.2],
        ["Others", 0.7]
      ];
    } else if (details === "hola") {
      dataValue = [
        ["Apple", 35],
        ["Guava", 40],
        ["Grapes", 22.5]
      ];
    }
    setChartOptions((prev) => {
      return {
        ...prev,
        series: [
          {
            type: "pie",
            name: "Browser share",
            data: dataValue
          }
        ]
      };
    });
  }, [details]);

  async function newfetchVendor(e) {
    if (!!e) {
      setDetails(e.target.value);
    }
  }

  return (
    <div>
      <select onChange={newfetchVendor}>
        <option value="sup">sup</option>
        <option value="hola">hola</option>
      </select>
      <PieChart
        highcharts={Highcharts}
        options={chartOptions}
        oneToOne={true}
      />
    </div>
  );
};

render(<App />, document.getElementById("root"));


编辑 Highcharts React Demo(分叉)


推荐阅读