微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 console.log 反转 API 调用中的数据顺序

如何解决使用 console.log 反转 API 调用中的数据顺序

使用 React 和 ChartJS-2 构建 Covid 跟踪器我发现我无法通过通常的方式来反转传入的数据,即。通过 chartJS 文档中的建议。似乎有效的是 console.log(res.data.data.reverse()) 如果没有将这行代码打印到控制台,数据会以相反的方式显示。 这是为什么?

xAxes 参数也不生效,但我可能只是在某处缺少一个 '}' 或 ']'。

import { useState,useEffect } from 'react';
import { Line } from 'react-chartjs-2';
import axios from 'axios';

const CovidCases = () => {
  const [chartData,setChartData] = useState({});

  const chart = () => {
    //set variables to pass in as dynamic data
    let covCase = [];
    let covDate = [];

    // axios get endpoint
    axios
      .get(
        'https://api.coronavirus.data.gov.uk/v1/data?filters=areaName=England;areaType=nation&structure={"date":"date","name":"areaName","code":"areaCode","newCasesByPublishDate":"newCasesByPublishDate","cumCasesByPublishDate":"cumCasesByPublishDate","newDeaths28DaysByPublishDate":"newDeaths28DaysByPublishDate","cumDeaths28DaysByPublishDate":"cumDeaths28DaysByPublishDate"}',)
   
      .then((res) => {
        // here I reverse the order that the data comes into the console
        console.log(res.data.data.reverse());

     
        for (const dataObj of res.data.data) {
          covCase.push(parseInt(dataObj.newCasesByPublishDate));
          covDate.push(parseInt(dataObj.date));

          // setting the chart data STATE with the chart.js labels and datasets with data: covCase variable
          setChartData({
            // https://www.chartjs.org/docs/latest/getting-started/usage.html for layout requirements
            labels: covDate,datasets: [
              {
                label: 'New Covid Cases by Date (England)',data: covCase,backgroundColor: ['rgba(81,250,157,0.6)'],borderWidth: 2,},],});
        }
      })
      .catch((err) => {
        console.log(err);
      }).catch((err) => {
        console.log(err.message)
      })
    // console.log(covCase,covDate);
  };

  useEffect(() => {
    chart();
  },[]);

  return (
    <div className="charts" style={{ height: 700,width: 900 }} >
      <Line
        // passing in the STATE as the data to be rendered
        data={chartData}
        // chart.js options parameters
        options={{
          title: { text: 'Covid Cases',display: true },scales: {
            yAxes: [
              {
                ticks: {
                  autoSkip: true,beginAtZero: true,xAxes: [
              {
                autoSkip: true,padding: 10,// this section didn't make the difference expected of it. reversing the console.log() did,though!!
                // ticks: {
                //   // reverse: true,//   maxTicksLimit: 7,//   display: false,// },}}
      />
    </div>
  );
};

export default CovidCases;

此外,xAxes 参数不起作用,但我认为我在代码建议范围内?

谢谢。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。