在 React 中获取数据

Fetching the data in React

我正在尝试绘制图表以从 Web Api 获取数据。我可以看到一些数据正在通过,但我仍然无法绘制图表。如果我做错了什么,请告诉我。

import React, { Component } from 'react';
import './main.styles.scss';
import { createChart } from 'lightweight-charts';

async function getData() {
  const response = await fetch(`http://localhost:3500/stock/app/RY`);
  const data = await response.json();
  return data.webApiData;
}

class Main extends Component {
  ref = React.createRef();

  componentDidMount() {
    const chart = createChart(this.ref.current, {
      width: 1400,
      height: 550,
      timeScale: {
        timeVisible: true,
        secondsVisible: false,
      },
    });

    const candleSeries = chart.addCandlestickSeries();

    const chartData = getData().then((data) => {
      console.log(data);
      candleSeries.setData(data);
    });
  }

  render() {
    return (
      <div className="main">
        <div className="trading">
          <div className="box one">1</div>
          <div className="box two" ref={this.ref}></div>
        </div>
      </div>
    );
  }
}

export default Main;

这是console.log上的数据

这是我遇到的错误

因为time格式不正确。它应该是一个日期字符串。

来自烛台图表docs

Each item of the candlestick series is either an OHLC or a whitespace item.

所以time必须是下面的格式。

const ohlcItem = {
    time: '2018-06-25',
    open: 10,
    high: 12,
    low: 9,
    close: 11,
};

// note it might be any type of series here
const series = chart.addHistogramSeries();

series.setData([
    { time: '2018-12-01', value: 32.51 },
    { time: '2018-12-02', value: 31.11 },
    { time: '2018-12-03', value: 27.02 },
    { time: '2018-12-04' }, // whitespace
    { time: '2018-12-05' }, // whitespace
    { time: '2018-12-06' }, // whitespace
    { time: '2018-12-07' }, // whitespace
    { time: '2018-12-08', value: 23.92 },
    { time: '2018-12-09', value: 22.68 },
    { time: '2018-12-10', value: 22.67 },
    { time: '2018-12-11', value: 27.57 },
    { time: '2018-12-12', value: 24.11 },
    { time: '2018-12-13', value: 30.74 },
]);

因为time属性的格式格式不正确。 它应该是 YYYY-MM-DD 风格。

比如你可以试试

const chartData = getData().then((data) => {
   console.log(data);
   candleSeries.setData(data.map((sD) => {
       return {time: `${sD.time.year}-${sD.month > 9 ? sD.month : `0${sD.time.month}`}-${sD.day > 9 ? sD.day : `0${sD.day}`}`, ...sD}
   }));
});