Не можем ли мы передать состояние в базу данных реагирующих диаграмм: наборы данных: данные? - PullRequest
0 голосов
/ 26 марта 2019

Я пытаюсь получить данные из sqlserver и хочу представить их в виде гистограммы, используяactchart.js. Я вытащил данные из sqlserver и установил их состояние. Почему я не могу использовать состояние в панели данных реактивной диаграммы?

Я получаю следующую ошибку. Я новичок, чтобы реагировать, что я здесь упускаю.

EditComponent.js: 41 Uncaught TypeError: Невозможно прочитать свойство 'Результаты выполнения' неопределенного

import React from "react";
import { Bar } from "react-chartjs-2";
import axios from "axios";

class ChartsPage extends React.Component {
  constructor(props) {
    super(props);
    //this.props.pass=[];
    //this.props.fail=[];
    this.state = { executionresults: [] };
  }

  componentDidMount() {
    axios
      .get("http://localhost:5000/modulewise")
      .then(response => {
        // console.log(response.data.recordset);
        // console.log(response.data.recordset[0].moduleName);
        // this.setState({ chartlabels: response.data.recordset.moduleName,chartpass: response.data.recordset.PASS,chartfail: response.data.recordset.FAIL });
        this.setState({ executionresults: response.data.recordset });
        // console.log(this.state.executionresults);
        const pass = this.state.executionresults.map(result => result.PASS);
        console.log(
          this.state.executionresults.map(result => result.moduleName)
        );
        console.log(this.state.executionresults.map(result => result.PASS));
        console.log(this.state.executionresults.map(result => result.FAIL));
        console.log(this.props.pass);
      })
      .catch(function(error) {
        console.log(error);
      });
  }

  state1 = {
    dataBar: {
      labels: this.state.executionresults.map(result => result.moduleName), //["AccountManagement", "BeneficiaryManagement", "CreditCards", "Incidents_Complaints", "Investments", "IPO", "LeaseTransfer", "QuickPay", "SADAD"],//["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"], //this.state.modstate,//
      //this.state.executionresults.map(result=> result.moduleName),//
      datasets: [
        {
          label: "PASS",
          data: [0, 2, 4, 1, 0, 0, 6, 0, 35], //[12, 39, 3, 50, 2, 32, 84], //this.state.passstate,//
          backgroundColor: "Green", //rgba(245, 74, 85, 0.5)
          borderWidth: 1
        },
        {
          label: "FAIL",
          data: [2, 4, 17, 10, 6, 1, 11, 5, 18], //[56, 24, 5, 16, 45, 24, 8], //this.state.failstate,//
          backgroundColor: "orange", //"rgba(90, 173, 246, 0.5)",
          borderWidth: 1
        }
      ]
    },
    barChartOptions: {
      responsive: true,
      maintainAspectRatio: true,
      scales: {
        xAxes: [
          {
            barPercentage: 1,
            gridLines: {
              display: true,
              color: "rgba(0, 0, 0, 0.1)"
            }
          }
        ],
        yAxes: [
          {
            gridLines: {
              display: true,
              color: "rgba(0, 0, 0, 0.1)"
            },
            ticks: {
              beginAtZero: true
            }
          }
        ]
      }
    }
  };

  render() {
    return (
      <div>
        <Bar data={this.state1.dataBar} options={this.state1.barChartOptions} />
      </div>
    );
  }
}

export default ChartsPage;

1 Ответ

0 голосов
/ 26 марта 2019

Проблема в том, что this in state1 ссылается на объект state1, но не на экземпляр компонента!

Чтобы передать правильные данные, вы можете изменить их на лету, используя .map метод массива. Я думаю, вам не нужно state1 вообще. Добавление const data в метод render можно использовать, поскольку вы можете подготовить необходимые данные перед передачей их компоненту <Bar />.

render() {
    const data = {
        dataBar: {
            labels: this.state.executionresults.map(result => result.moduleName), 
            datasets: [
                {
                    label: "PASS",
                    data: [0, 2, 4, 1, 0, 0, 6, 0, 35], 
                    backgroundColor: "Green", 
                    borderWidth: 1
                },
                {
                    label: "FAIL",
                    data: [2, 4, 17, 10, 6, 1, 11, 5, 18], 
                    backgroundColor: "orange",
                    borderWidth: 1
                }
            ]
        },
        barChartOptions: {
            responsive: true,
            maintainAspectRatio: true,
            scales: {
                xAxes: [
                    {
                        barPercentage: 1,
                        gridLines: {
                            display: true,
                            color: "rgba(0, 0, 0, 0.1)"
                        }
                    }
                ],
                yAxes: [
                    {
                        gridLines: {
                            display: true,
                            color: "rgba(0, 0, 0, 0.1)"
                        },
                        ticks: {
                            beginAtZero: true
                        }
                    }
                ]
            }
        }
    };

    return (
      <div>
        <Bar data={data.dataBar} options={data.barChartOptions} />
      </div>
    );
  }
...