【问题标题】:ChartJS+React: toggle showLine in scatter view doesn't workChartJS+React:在散点视图中切换 showLine 不起作用
【发布时间】:2022-10-18 15:06:58
【问题描述】:

我有一个使用 ChartJS 和 React 的简单散点图。散点图通常可以通过在数据集中设置选项“showLine”来连接单个数据点之间的线。我想要一个按钮来切换此选项(打开/关闭 showLines)。不幸的是,这不起作用。

如果 initalDataSet 中的 showLines 为 true,则更改为 false 不会执行任何操作。如果 initalDataSet 中的 showLines 为 false,将其更改为 true 会使 ChartJS 崩溃,并出现以下错误:

Uncaught TypeError: line is null

这是所描述问题的一个简单示例:

import React, {
  useEffect,
  useReducer,
} from "react";
import { Scatter } from "react-chartjs-2";
import Chart from "chart.js/auto";

const initalDataSet = {
  datasets: [
    {
      label: "dataset1",
      data: [
        {
          x: 1,
          y: 10,
        },
        {
          x: 3,
          y: 15,
        },
        {
          x: 5,
          y: 5,
        },
        {
          x: 7,
          y: 8,
        },
      ],
      borderColor: "red",
      showLine: false,
    },
    {
      label: "dataset2",
      data: [
        {
          x: 2,
          y: 4,
        },
        {
          x: 4,
          y: 6,
        },
        {
          x: 6,
          y: 12,
        },
        {
          x: 8,
          y: 18,
        },
        {
          x: 10,
          y: 10,
        },
        {
          x: 12,
          y: 15,
        },
        {
          x: 14,
          y: 5,
        },
        {
          x: 16,
          y: 8,
        },
      ],
      borderColor: "blue",
      showLine: false,
    },
  ],
};

const processData = (state, action) => {
  switch (action.type) {
    case "TOGGLE_LINE":
      return {
        ['datasets']: state.datasets.map((item) => ({
          ...item,
          showLine: (!item['showLine']),
        })),
      };
    default:
      return state;
  }
};

function App() {
  const [plotData, dispatch] = useReducer(processData, initalDataSet);

  useEffect(() => {
    console.log("debug --->", { datasets: Object.values(plotData) });
  }, [plotData]);

  return (
    <div className="App">
      <header className="App-header">
        <button
          onClick={() => {
            dispatch({ type: "TOGGLE_LINE" });
          }}
        >
          Toggle Line View
        </button>
        <Scatter data={plotData} />
      </header>
    </div>
  );
}

export default App;

我认为它必须与 ChartJS 组件的重新渲染有关,但我不知道如何解决它。有谁知道如何做到这一点?

谢谢!

【问题讨论】:

标签: react-hooks chart.js react-chartjs-2


【解决方案1】:

可以在here 找到此错误的可能解决方案/解决方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-20
    相关资源
    最近更新 更多