1

希望在 react-vis 中开始一些图形,并且想知道将数据从 json 推送到状态的最佳方法是什么,以便我可以从图形中访问状态数据。下面是我的测试json:

[
    {
      "day": "1",
      "flights":"58",
      "passengers": "6076"
    },
    {
        "day": "2",
        "flights": "78",
        "passengers": "7089"
    },
    {
        "day": "3",
        "flights": "101",
        "passengers": "9760"
    }
] 

我本质上想将“day”和“flights”推送到数据数组中,以模仿 react-vis 提供的示例。下面是我的代码:

应用程序.js

//import logo from './logo.svg';
//import './App.css';
import React, { Component } from 'react';
import my_data from './data/csvjson.json';
import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries,
   VerticalGridLines, LineMarkSeries} from 'react-vis';
import '../node_modules/react-vis/dist/style.css';

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
     data:[]
  }
  }

  //react vis documentation points to data being an object like so:
   //sample data 
   //data:[
   // {x: 0, y: 8},
   // {x: 1, y: 5},
   // {x: 2, y: 4}
  // ]

  render() {
    return (
      <div>

        <XYPlot width={400} height={300}><XAxis/><YAxis/>
          <HorizontalGridLines />
          <VerticalGridLines />
          <LineMarkSeries data={this.state.data} />
        </XYPlot>
      </div>
    );
  }
}

export default App;
4

2 回答 2

2

您需要对其进行预处理my_data并将其存储在状态中。应该有一个函数映射my_data并返回具有 x 和 y 属性的对象的数组{x: day, y: flight}

import React, { Component } from 'react';
import { render } from 'react-dom';
import my_data from './data/csvjson.json';
import {XYPlot, XAxis, YAxis, HorizontalGridLines, LineSeries,
   VerticalGridLines, LineMarkSeries} from 'react-vis';

const processData = (data) => {
  return data.map(e => ({
    x: e.day,
    y: e.flights
  }));
};

class App extends Component {
  constructor() {
    super();
    this.state = {
      data: processData(my_data)
    };
  }

  render() {
        return (
      <div>
          <XYPlot width={400} height={300}><XAxis/><YAxis/>
          <HorizontalGridLines />
          <VerticalGridLines />
          <LineMarkSeries data={this.state.data} />
        </XYPlot>
      </div>
    );
  }
}

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

我也在 stackblitz 上做过,你可以在那里查看现场演示:https ://stackblitz.com/edit/react-abkc1j

于 2019-10-29T16:07:50.253 回答
0

您想要做的只是使用您从某个 API 检索到的数据创建一个新数组。这最简单地通过.map. 你可以运行这样的东西:

jsonData.map((entry) => ({x: entry.day, y: entry.flights}))

于 2019-10-29T16:04:51.217 回答