简体   繁体   English

Chart.js 图表显示但没有数据

[英]Chart.js Chart displays but no data

I'm using React with react-chartjs-2 I'm passing the data to the data.我将 React 与 react-chartjs-2 一起使用,我将数据传递给数据。 But I am getting a Graph without data.但我得到一个没有数据的图表。

ATT: inside the data I'm mapping a product object ATT:在数据中我正在映射一个产品 object

在此处输入图像描述

 const [chartData, setChartData] = useState({})
    const products= [
        {name: "PC", solds: 34},
        {name: "Mouce", solds: 55},
        {name: "keyboard", solds: 6},
        {name: "Process", solds: 2},
    ]
    const chart = () => {
        setChartData({
            labels: ['PC', 'Mouse', 'Keyboard', 'Process' ],
            datasets: [{
                label: 'Level of Thiccness',
                data: [Object.entries(products).map(sold=> sold.solds)],
                backgroundColor: [
                    'rgba(75, 192, 192, 0.6)'
                ],
                borderWidth: 4
            }]
        })
    }

    useEffect(() => {
        chart();
    }, [])
    return (
        <div>
            <Line 
            data={chartData}
            />
        </div>
    )
}

your data in datasets params is not well formated,您在数据集参数中的数据格式不正确,
try this:尝试这个:

const [chartData, setChartData] = useState({});
  const products = [
    { name: "PC", solds: 34 },
    { name: "Mouce", solds: 55 },
    { name: "keyboard", solds: 6 },
    { name: "Process", solds: 2 }
  ];
  const chart = () => {
    const dataValue = products.map(prod=>prod.solds);
    setChartData({
      labels: ["PC", "Mouse", "Keyboard", "Process"],
      datasets: [
        {
          label: "Level of Thiccness",
          data: dataValue,
          backgroundColor: ["rgba(75, 192, 192, 0.6)"],
          borderWidth: 4
        }
      ]
    });
  };

  useEffect(() => {
    chart();
  }, []);

  return (
    <div>
      <Line data={chartData} />
    </div>
  );

here you can find an example在这里你可以找到一个例子
UPDATE更新
you can do the same for your labels param:你可以对你的标签参数做同样的事情:

const chart = () => {
    const dataValue = products.map((prod) => prod.solds);
    const labelList = products.map((prod) => prod.name);
    setChartData({
      labels: labelList,
      datasets: [
        {
          label: "Level of Thiccness",
          data: dataValue,
          backgroundColor: ["rgba(75, 192, 192, 0.6)"],
          borderWidth: 4
        }
      ]
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM