React ChartJS空状态axios调用

时间:2018-08-13 23:41:22

标签: reactjs charts react-chartjs

我正在尝试从ChartJS中的api绘制加密硬币。 Axios调用进展顺利,并获取了键值对的对象。但是,当我想将setState推入图表(数据属性)并记录状态时,它仅返回两个空的数据集和标签数组

    import React, { Component } from "react";
import Chart from "./components/Chart";
import axios from "axios";
class App extends Component {
  state = {
    chartData: {}
  };

  componentWillMount() {
    this.getChartData();
  }

  getChartData() {
    axios
      .get(
        "https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=BTC,USD,EUR"
      )
      .then(res => {
        const coin = res.data;
        const result = Object.values(coin)[0];
        this.setState({
          chartData: {
            labels: [
              "Boston",
              "Worcester",
              "Springfield",
              "Lowell",
              "Cambridge",
              "New Bedford"
            ],
            datasets: [
              {
                label: "Population",
                data: result,
                backgroundColor: [
                  "rgba(255, 99, 132, 0.6)",
                  "rgba(54, 162, 235, 0.6)",
                  "rgba(255, 206, 86, 0.6)",
                  "rgba(75, 192, 192, 0.6)",
                  "rgba(153, 102, 255, 0.6)",
                  "rgba(255, 159, 64, 0.6)",
                  "rgba(255, 99, 132, 0.6)"
                ]
              }
            ]
          }
        });
      });
    console.log(this.state);
  }
  render() {
    return (
      <div className="App">

        <Chart
          chartData={this.state.chartData}
          location="Massachusetts"
          legendPosition="bottom"
        />
      </div>
    );
  }
}

export default App;

1 个答案:

答案 0 :(得分:0)

setState不再同步setState,因此最好将console.log(this.state);放在render()中。

您会注意到render()被调用了两次。一次用于初始渲染,第二次一次用于setState实际上设置状态。

我将在您的loading函数中添加一个变量来跟踪axios调用的render()状态,并在完成加载后呈现图表。

编辑: 最简单的解决方案是在数据准备就绪之前不渲染任何内容:

render() {
    if(!this.state.chartData.datasets[0].data){return null}
    else {
        return (
          <div className="App">
            <Chart
              chartData={this.state.chartData}
              location="Massachusetts"
              legendPosition="bottom"
            />
          </div>
        );
    }     
}