试图用反应来提出一个高图。我有多个fetch api调用(为了说明,我只添加了2个),我将使用它来在UI中呈现内容。
在此示例中,data1用于呈现表,data2用于呈现高图。
我将这些调用的输出存储在状态对象中。当我调用这些API时,我获取数据但无法将其设置为highcharts的“series”属性以进行渲染,因此没有任何内容被渲染。
“api2”:[{“name”:“Test1”,“value”:12},{“name”:“Test2”,“value”:9}]
有人可以帮我弄这个吗?我哪里错了?
我正在使用highcharts-react-official
import * as React from 'react';
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official';
interface IState {
data1: [];
data2: [];
}
interface IProps {}
class Example extends React.Component<IProps,IState> {
constructor(props:any)
{
super(props);
this.state = {
data1: [],
data2: []
}
}
componentDidMount()
{
Promise.all([
fetch('http://localhost:3001/api1'),
fetch('http://localhost:3001/api2')
])
.then(([res1, res2]) => Promise.all([res1.json(), res2.json()]))
.then(([data1, data2]) => this.setState({
data1: data1,
data2: data2
}));
}
render() {
let options:any;
options = {
chart: {
type: 'column'
},
credits: false,
exporting: {enabled: false},
title: {
text: ''
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'bottom'
},
xAxis: {
visible:false
},
yAxis: {
visible:false
},
plotOptions: {
column: {
dataLabels: {
enabled: true }
}
},
series: this.state.data2
};
return(
<div className="an-content">
//some table rendering will happen here
<HighchartsReact
highcharts={Highcharts}
options={options}
/>
</div>
)
}
}
export default Example;
您需要提供Highcharts所需的数据格式:
this.setState({
data2: data2.map(x => ({ name: x.name, data: [x.value] }))
});
现场演示:https://codesandbox.io/s/7w2pw4p900
API参考:https://api.highcharts.com/highcharts/series.column.data