【问题标题】:How to fetch data into highchart in react app如何在反应应用程序中将数据提取到highchart
【发布时间】:2020-03-19 13:43:40
【问题描述】:

是否可以使用 json 数据获取 highcharts,https://www.npmjs.com/package/highcharts?我正在使用反应应用程序。我尝试这种静态方式:

import React from 'react'
import { render } from 'react-dom'
import Highcharts from 'highcharts'
import HighchartsReact from 'highcharts-react-official'

const options = {
    title: {
      text: 'My chart'
 },
  series: [{
   data: [1, 2, 3]
   }]
 }

 const App = () => <div>
 <HighchartsReact
  highcharts={Highcharts}
  options={options}
 />
 </div>

 render(<App />, document.getElementById('root'))

它可以工作,但我希望显示我的数据。 我的 json 看起来像:

 [
  {
    "Date": "2019-10-29",
    "Price1": 55.34,
    "Price2": 61.05,
    "Price3": 1.791
  },
  {
    "Date": "2019-10-28",
    "Price1": 55.6,
    "Price2": 60.39,
    "Price3": 1.784
  }
]

【问题讨论】:

  • componentDidMount -> fetch 数据 -> setState -> 将state.options 传递给HighcartsReact 组件

标签: json reactjs api highcharts


【解决方案1】:

您可以在componentDidMount / useEffect函数中获取数据并更新某个状态下的图表选项,例如:

const App = () => {
  const [options, setOptions] = useState({
    title: {
      text: "My chart"
    },
    series: [{ data: [] }]
  });

  useEffect(() => {
    fetch("https://api.myjson.com/bins/7lxy4")
      .then(response => {
        return response.json();
      })
      .then(data => {
        setOptions({ series: [{ data: data }] });
      });
  }, []);

  return <HighchartsReact highcharts={Highcharts} options={options} />;
};

现场演示: https://codesandbox.io/s/highcharts-react-demo-v47y7

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-14
  • 2018-10-30
  • 2010-11-08
相关资源
最近更新 更多