【问题标题】:Undefined values when try to Insert array in component尝试在组件中插入数组时未定义的值
【发布时间】:2018-08-05 02:06:01
【问题描述】:

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

[
  {
    "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!"}
    ]
  } ]

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

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;

但在反应中它无法编译导致color_top_data, day_top_data, value_top_data 未定义。有人可以帮忙吗?

【问题讨论】:

  • 声明 var day_top_data; var value_top_data;全球应该工作
  • @G_S 我试过了,它显示 Cannot read property 'GraphData' of undefined 所以我猜这个问题是因为 this.props.graphData[0] 没有定义(没有将值传递给 this.props.graphData[0]
  • 'If (this.props.graphData) { }'
  • 你从哪里获得 topdata 的道具?我怀疑那是否是无状态组件
  • 这一行 var topdata = this.props.graphData[0].map((graph, i) =&gt; { 你正试图在 React 组件之外使用 this.props。你应该在 React 类组件中使用 this.props

标签: reactjs chart.js


【解决方案1】:

根据您的代码和 cmets,我认为您正在努力实现以下目标:

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>
    )
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 1970-01-01
    相关资源
    最近更新 更多