与来自 api rest 的数据反应时渲染图形时出错

我正在尝试使用来自 api rest 的数据来呈现图表,但它没有显示值。我试图检查 chartjs 文档,但找不到错误。有谁能够帮助我?我正在使用反应、图表和 axios。


import React, { useState } from "react";

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

import axios from "axios";


export default function ChartBar() {

  const [dados, setDados] = useState({});


  async function consultApi() {

    let res = await axios.get(

      "https://private-afe609-testefront.apiary-mock.com/anual-result"

    );

    Object.values(res.data).map(item => setDados(item));


  }

  console.log(dados);


  consultApi();


  return (

    <div>

      <Bar labels={[dados.label]} data={[dados.value]} />

    </div>

  );

}


拉风的咖菲猫
浏览 69回答 1
1回答

慕沐林林

我认为你在这里遗漏了很多东西检查图表 js 2 如何检索数据道具以及您如何处理 API 响应。这会奏效在这里检查沙箱import React, { useState } from "react";import { Bar } from "react-chartjs-2";import axios from "axios";export default function App() {&nbsp; const [label, setLabel] = useState([]);&nbsp; const [data, setData] = useState([]);&nbsp; React.useEffect(() => {&nbsp; &nbsp; axios&nbsp; &nbsp; &nbsp; .get("https://private-afe609-testefront.apiary-mock.com/anual-result")&nbsp; &nbsp; &nbsp; .then(result => {&nbsp; &nbsp; &nbsp; &nbsp; setLabel(Object.keys(result.data).map(key => result.data[key].label));&nbsp; &nbsp; &nbsp; &nbsp; setData(Object.keys(result.data).map(key => result.data[key].value));&nbsp; &nbsp; &nbsp; &nbsp; console.log(data);&nbsp; &nbsp; &nbsp; });&nbsp; }, []);&nbsp; return (&nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; <Bar data={{&nbsp; &nbsp; &nbsp; &nbsp; labels: label,&nbsp; &nbsp; &nbsp; &nbsp; datasets: [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; label: 'My First dataset',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; backgroundColor: 'rgba(255,99,132,0.2)',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; borderColor: 'rgba(255,99,132,1)',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; borderWidth: 1,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hoverBackgroundColor: 'rgba(255,99,132,0.4)',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; hoverBorderColor: 'rgba(255,99,132,1)',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; data: data&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; &nbsp; }} />&nbsp; &nbsp; </div>&nbsp; );}const rootElement = document.getElementById("root");ReactDOM.render(&nbsp; <React.StrictMode>&nbsp; &nbsp; <App />&nbsp; </React.StrictMode>,&nbsp; rootElement);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript