1

我正在尝试从 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;
4

1 回答 1

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>
        );
    }     
}
于 2018-08-14T00:32:35.200 回答