如何使用 React hooks 更新 HighChart 中的配置?

How to update config in HighChart with React hooks?

我想通过 useState 更改 HighChart 的选项。 然后我可以使用按钮单击重新呈现图表。

这是我的代码:

const options = {
  title: {
    text: "My chart",
  },
  series: [
    {
      data: [1, 2, 3, 7, 2, 3, 1, 0],
    },
    {
      data: [1, 2, 1, 7, 3, 3, 3, 0],
    },
  ],
};

export default function HighChartContainer() {
  const [chartOptions, setChartOptions] = useState(options);

  const handleChangeOptions = () => {
    const newLineData = [
      {
        data: [1, 2, 1, 4, 2, 3, 7, 0],
      },
      {
        data: [1, 2, 1, 6, 3, 5, 2, 0],
      },
    ];
    const newOptions = { ...chartOptions, series: newLineData };
    setChartOptions(newOptions);
  };
  return (
    <div>
      <ChartWrapper>
        <HighchartsReact
          highcharts={Highcharts}
          options={chartOptions}
        />
      </ChartWrapper>
      <div>
        <button type="button" onClick={handleChangeOptions}>
          Click me
        </button>
      </div>
    </div>
  );
}

没用。我尝试了 google,但找不到以这种模式编写代码的人。 有什么问题吗?

我的代码沙盒: https://codesandbox.io/s/serene-framework-jjoh4?file=/src/App.js

在你更新问题之后。我看到问题是你在 HighchartsReact 中传递了 callback={handleChangeOptions}。所以你只需删除它。一切正常。

您需要从回调中删除 handleChangeOptions 才能看到效果。此外,仅使用新选项更新图表就足够了:

const handleChangeOptions = () => {
  const newLineData = [
    {
      data: [...]
    },
    {
      data: [...]
    }
  ];
  const newOptions = { series: newLineData };
  setChartOptions(newOptions);
};

现场演示: https://codesandbox.io/s/angry-johnson-gpv99?file=/src/App.js

文档: https://github.com/highcharts/highcharts-react#optimal-way-to-update