我正在使用Highcharts进行一个React项目,以渲染一个朝阳图表。该图表应该可视化从API获取的数据,但它没有渲染,并且控制台中没有错误。我怀疑问题可能与我为Highcharts转换数据的方式有关。
下面是组件代码:
import React from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import sunburst from "highcharts/modules/sunburst";
import { useQuery } from "@tanstack/react-query";
function extractData(data) {
const ids = [];
const labels = [];
const parents = [];
const values = [];
function traverse(element, parentId) {
if (element.children) {
element.children.f`your text`orEach((child) => {
if (child.Código && child["Sub-Setor"]) {
ids.push(child.Código);
labels.push(child["Sub-Setor"]);
parents.push(parentId);
values.push(child["Part. (%)"]);
}
if (child.children) {
traverse(child, child.name);
}
});
}
}
data.forEach((sector) => {
if (sector.children) {
sector.children.forEach((subSector) => {
traverse(subSector, sector.name);
});
}
});
return { ids, labels, parents, values };
}
function fetchData() {
return fetch("http://rar.xxx.xxx/api/indices/data/IBOV").then((res) =>
res.json()
);
}
// Inicializa o módulo Sunburst
sunburst(Highcharts);
function SunburstChart({ data }) {
const { data: indices, isLoading, error } = useQuery(["sunburst"], fetchData);
if (isLoading) {
return <p>Carregando...</p>;
}
if (error) {
return <p>Ocorreu um erro: {error.message}</p>;
}
const extratedData = extractData(indices);
console.log(extratedData);
// Configura as opções do gráfico
const options = {
series: [
{
type: "sunburst",
data: extratedData,
allowDrillToNode: true,
cursor: "pointer",
dataLabels: {
format: "{point.name}",
},
},
],
title: {
text: "Meu Gráfico Sunburst",
},
};
return <HighchartsReact highcharts={Highcharts} options={options} />;
}
export default SunburstChart;
字符串
extractData函数应该将API数据整形为适合Highcharts的格式,但图表仍然是空白的。转换后的数据如下所示:
对象
id:[“EMBR3”,“AZUL4”,“CCRO3”,“GOLL4”,“RAIL3”,“BRFS3”,“JBSS 3”,“MRFG3”,“BEEF 3”,“SMTO 3”,.](85)
标签:[“Mat Transporte”,“Transporte”,“Transporte”,“Transporte”,“Transporte”,“Transporte”,“Alimentos Processados”,“Alimentos Processados”,“Alimentos Processados”,“Alimentos Processados”,.](85)
家长:[“Bens Indls”,“Bens Indls”,“Bens Indls”,“Bens Indls”,“Bens Indls”,“Consumo Nabio-Cíclico”,“Consumo Nabio-Cíclico”,“Consumo Nabio-Cíclico”,“Consumo Nabio-Cíclico”,“Consumo Nabio-Cíclico”,.](85)
值:[0.667,0.261,0.591,0.082,1.305,1.092,1.127,0.11,0.084,0.224,...](85)
我期待一个朝阳图表,显示行业,子行业和股票代码及其相应的值,但图表容器保持空,没有任何错误消息。有人能帮助我确定extractData函数的错误或数据如何传递到Highcharts吗?
...........................................................
1条答案
按热度按时间8aqjt8rx1#
你需要调整你的数据以适应Highcharts所要求的结构,所以是一个对象数组,而不是一个带数组的对象。
下面你可以找到一个如何转换现有结构的例子。
字符串
现场演示:https://jsfiddle.net/om61vsk3/
API引用:https://api.highcharts.com/highcharts/series.sunburst.data