React Highchart JS xAxis标签

时间:2020-10-18 14:31:51

标签: reactjs typescript highcharts

我正在使用Highcharts通过Websocket可视化数据。 传入数据的格式为:

enter image description here

Highcharts仍将xAxis显示为介于0到100之间的数值。 我该如何从dataPoint对象那里获得created_time?

我尝试了xAxis Formatter,但是格式化此数值不会给我datetime对象或datetime字符串。我将数据点对象作为道具传递,因此我也尝试访问this.props.dataPoint.created_time, 但是不幸的是,当我启动应用程序时,this.props.dataPoint处于未定义的开头。

这是图表组件的代码:

import * as React from 'react';
import Highcharts from 'highcharts';
import HighchartsReact from 'highcharts-react-official';
import { SensorData } from './types';
import { slidingTimeWindowSec } from './utils';

// noinspection TsLint
const Boost = require('highcharts/modules/boost');
Boost(Highcharts); // WebGL-backed rendering (https://www.highcharts.com/blog/tutorials/higcharts-boost-module/)

type Props = {
    readonly dataPoint: SensorData
}

class HighchartsTimeSeries extends React.Component<Props, {}> {

    private readonly renderToId = 'highcharts-container'
    private chart: Highcharts.Chart | undefined

    constructor(props: Props) {
        super(props)
    }

    public componentDidMount() {
        // @ts-ignore
        this.chart = (Highcharts as any).chart({
            title: {
                text: 'Live Data via WebSocket'
            },
            xAxis: {
                type: 'datetime',
                labels: {
                    step: 2,
                },
            },
            yAxis: {
                min: 0,
                max: 80
            },
            series: [{
                type: "area",
                name: 'Temperatur C',
                data: this.props.dataPoint
            }],
            chart:{
                renderTo: this.renderToId
            }
        })
        requestAnimationFrame(this.redrawChart)
    }

    public componentDidUpdate() {
        // @ts-ignore
        const series = this.chart.series[0];
        const firstPoint = series.data[0];
        const shouldShift = series.data[0] ? firstPoint.x < Date.now() - slidingTimeWindowSec * 1000 : false;
        series.addPoint([this.props.dataPoint.created_time, this.props.dataPoint.temperature], false, shouldShift, false);
    }

    public render() {
        return (
            <div id={this.renderToId}/>
        );
    }

    private redrawChart = () => {
        // @ts-ignore
        this.chart.redraw(false);
        requestAnimationFrame(this.redrawChart);
    }

}

export default HighchartsTimeSeries;

1 个答案:

答案 0 :(得分:0)

在将数据格式加载到图表之前,请尝试解析数据格式。像这样:

let data = [{
    created_time: "2020-10-18T11:53:07.948019+02:00",
    humidity: 74.09,
    id: 7103,
    light: 349.16,
    occupancy: true,
    people_count: 225,
    temperature: 19.200
}];

data.forEach(d => {
    d.x = Date.parse(d.created_time);
    d.y = d.temperature
})

演示:https://jsfiddle.net/BlackLabel/y9avzLsq/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse