尝试在组件中插入数组时未定义的值

时间:2018-02-25 14:29:41

标签: reactjs chart.js

我正在尝试将数组作为json文件中的数据传递:

var x = screen.availHeight + "px";
console.log(x)

document.getElementById("test").style.height = x;

使用Chartjs并根据using array values in chart.js data and label field我的组件代码如下:

[
  {
    "label": "label 1",
    "color": "#FFF000",
    "data": [
      {"x": "Day 1", "y": 69},
      {"x": "Day 2", "y": 71},
      {"x": "Day 3", "y": 45},
      {"x": "Day 4", "y": 72},
    ]
  }, {
    "label": "Overall Score",
    "color": "#444001",
    "datapoints": [
      {"x": "Day 1", "y": 48},
      {"x": "Day 2", "y": 57},
      {"x": "Day 3", "y": 50},  
      {"x": "Day 4", "y": 80, "tooltip": "Good Job!"}
    ]
  } ]

但是在反应中它无法编译原因import React, {Component} from 'react'; import {Line} from 'react-chartjs-2'; var topdata = this.props.graphData[0].map((graph, i) => { var color_top_data = graph.color; var label_top_data = graph.label; graph.datapoints.map((row, i) => { var day_top_data = row.x; var value_top_data = row.y; }); }); class LineChart extends Component { render() { return ( <div> <Line data={{ labels: day_top_data, datasets: [ { data: value_top_data, backgroundColor: color_top_data, fill: false, lineTension: 0.4, }] }} /> </div> ); } } export default LineChart; 未定义。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

根据您的代码和评论,我认为您正在努力实现这一目标:

import React, {Component} from 'react';
import {Line} from 'react-chartjs-2';

class LineChart extends Component {
  render() {
    const labels = this.props.GraphData.data.map(point => point.x)
    const data = this.props.GraphData.data.map(point => point.y)
    return (
      <div>
        <Line
          data={{
            labels,
            datasets: [{
              data,
              backgroundColor: this.props.GraphData.color,
              fill: false,
              lineTension: 0.4
            }]
          }} />
      </div>
    )
  }
}