React and chart.js with json

问题描述 投票:0回答:1

我是React和JS的新手。我正在尝试从JSON创建图形,但是我无法通过MAP函数和PUSH将值传递给图形,我的结果只是我手动输入的数字(2、3、5-第45行)

dataGraf.push(hit.minutos) //Works well

this.state.items.map((hit) => (dataGraf.push(hit.minutos))) //No erros, but no data add

我的JSON:

[
  {"indice":1,"minutos":569,"programa":"seg"}, 
  {"indice":2,"minutos":421,"programa":"ter"}, 
  {"indice":3,"minutos":258,"programa":"quar"}
]
import React,{Component} from 'react';
import Chart from "chart.js";
import Config from '../components/config.js';

let dataGraf = []

class GraphChart extends Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();

        this.state = {
            items: [],
            error: null
        };
      }

  componentDidMount() {
    let url1 = `${Config.FullURL}/progativo`
    const ctx = this.ctx;

    fetch(url1)
      .then(items => items.json())
      .then((items) => {
        this.setState({ items });
      });

      this.funDadosGrafico()

    new Chart(ctx, {
        type: "pie",
        data: {
          labels: ['blue', 'green','red'],
          datasets: [
            {
              label: "# of Likes",
              data: dataGraf
            }                
          ]
        }
      });
    } //End of componentDidMount

    funDadosGrafico(){
      dataGraf.push(2, 5, 3) //Just for test
      this.state.items.map((hit) => (
        dataGraf.push(hit.minutos)))
    }

    render() {
      return (
          <div>
              <canvas width='800' height='300' ref={ctx => (this.ctx = ctx)}/>
          </div>
      )
    }
}
export default GraphChart;
json reactjs chart.js
1个回答
0
投票

尝试将执行this.funDadosGrafico()和Canvas创建移动到componentDidUpdate。

一旦调用fetch,fetch不会阻塞线程,因此this.funDadosGrafico()会在向后执行。 then块仅在解析获取后才执行。

加上,setState方法也是异步的。即使您从fetch调用中删除setState,它也不会按预期工作:

this.setState(updateMyState)
this.funDadosGrafico() // not going to work also, setState is async
© www.soinside.com 2019 - 2024. All rights reserved.