首页 > 解决方案 > 使用 POST 调用的响应更新 Chartjs 数据?

问题描述

我目前正在使用 react-chartjs-2 能够将图表插入到反应组件中。我正在导入位于另一个 js 文件中的图表的数据和选项。在我的应用程序中,我还进行了一个 POST 调用,它在它的主体中返回一些数据,我想将这些数据用作图表的数据,并且图表能够在每次调用 POST 请求时进行更新。POST 响应当前存储在称为 RESTResponse 的状态中。因此,要在 react 中访问图表之外的响应数据,我通常会调用{this.state.RESTresponse.total}. 我希望能够{this.state.RESTresponse.total}用作图表中的数据。我怎么能做到这一点?如果我不为图表和主要组件使用两个单独的 js 文件会更容易吗?谢谢!

这是调用图表的代码:

import {HorizontalBar} from "react-chartjs-2";
import {Row} from "reactstrap";

// Importing the chart data and options to be used in <HorizontalBar>
import {stackedChart} from "variables/charts.js";

class Dashboard extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      RESTresponse: []
    };
  }  
  async onTodoChange(event){
    let updateJSON = {...this.state.RESTresponse, [event.target.name] : val}
    const requestOptions = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(updateJSON)
    };
    const response = await fetch('/api/calculate', requestOptions);
    const body = await response.json();
    this.setState({RESTresponse : body });
}

  render() {
    return (
      <>
        <div className="content">
          <Row>
            <HorizontalBar
              data={stackedChart.data}
              options={stackedChart.options}
            />
          </Row>
        </div>
      </>
    );
  }
}

这是定义数据和选项的代码:

let stackedChart = {
  data: canvas => {
    return {
      datasets: [
        {
          label: ' Total Value',
          data: [10], //<--- I want to dynamically update this data value from the POST response
          backgroundColor: '#C4D156'
        }
      ]
    };
  },
  options: {
    maintainAspectRatio: false,
    legend: {
      display: true,
      labels: {
        usePointStyle: true,
        borderWidth: 0,
        filter: function(legendItem, chartData) {
          if (legendItem.datasetIndex === 3) {
            return false;
          }
         return true;
         }
      }
    },
    tooltips: {enabled: false},
    hover: {mode: null},
    responsive: true,
    scales: {
      yAxes: [
        {stacked: true},
      ],
      xAxes: [{stacked: true,
        ticks: {
             display: false
        }
      },
      ]
    }
  }
};


module.exports = {
  stackedChart
};

标签: javascriptreactjsrestchart.jsreact-chartjs

解决方案


什么时候data是一个函数,它是用安装图表的节点调用的。但是,您目前似乎不需要它。

声明数据以接收服务器响应数据。

  dataFactory: data => {
    return {
      datasets: [
        {
          label: ' Total Value',
          data,
          backgroundColor: '#C4D156'
        }
      ]
    };
  },

然后在组件的 render 方法中调用它,并将数据存储在 state 中。

<HorizontalBar
  data={stackedChart.dataFactory(this.state.RESTresponse)}
  options={stackedChart.options}
/>
 

推荐阅读