如何使用 axios 和 React 从 API 响应访问有效负载属性

发布于 2025-01-14 02:18:50 字数 3803 浏览 1 评论 0原文

我正在尝试使用 axios 从 API 响应访问嵌套对象。我将使用 ChartJS 使用这些数据来绘制条形图。下面是我的代码。

import { ChartContainer, Container } from "../styled/BarChart";
import {
  Chart as ChartJS,
  BarElement,
  LinearScale,
  CategoryScale,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import { useEffect, useState } from "react";
import api from "../pages/api/posts";

ChartJS.register(BarElement, LinearScale, CategoryScale);

const BarChart = () => {
  const [chart, setChart] = useState<any[]>([]);
  const [load, setLoad] = useState<any[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await api.get(
          "/careRecipient/ad3512a6-91b1-4d7d-a005-6f8764dd0111/events/water_intake"
        );

        setChart(response.data);
        setLoad(Object.keys(JSON.parse(response.data.payload))); //FIX
        console.log(response.data);
      } catch (err) {
        // Not in the 200 response range
        let errorMessage = "Failed!";
        if (err instanceof Error) {
          errorMessage = err.message;
        }
        console.log(errorMessage);
      }
    };

    fetchData();
  }, []);

  const data = {
    labels: chart?.map((data) => data.timestamp),
    datasets: [
      {
        label: `${chart?.length} Fluid Intake Observations`,
        data: load?.map((data) => data.volume_ml), //NOT WORKING
        backgroundColor: [
          "rgba(255, 99, 132, 0.2)",
          "rgba(54, 162, 235, 0.2)",
          "rgba(255, 206, 86, 0.2)",
          "rgba(75, 192, 192, 0.2)",
          "rgba(153, 102, 255, 0.2)",
          "rgba(255, 159, 64, 0.2)",
        ],
        borderColor: [
          "rgba(255, 99, 132, 1)",
          "rgba(54, 162, 235, 1)",
          "rgba(255, 206, 86, 1)",
          "rgba(75, 192, 192, 1)",
          "rgba(153, 102, 255, 1)",
          "rgba(255, 159, 64, 1)",
        ],
        borderWidth: 1,
      },
    ],
  };

  const options = {
    maintainAspectRatio: false,
    scales: {
      y: {
        beginAtZero: true,
      },
    },
    legend: {
      labels: {
        fontSize: 26,
      },
    },
  };

  return (
    <Container>
      <ChartContainer>
        <Bar data={data} options={options} height={400} />
      </ChartContainer>
    </Container>
  );
};

export default BarChart;

我收到的响应采用这种格式,并且我收到了其中多个:

RowDataPacket {
    payload: '{"id": "fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed", "note": "", "visit_id": "8e1dd351- 
    9178-45d1-be2d-673692c2e6ac", "timestamp": 
    "2019-04-26T12:42:07.088Z", "volume_ml": 400, 
    "event_type": "water_intake", "caregiver_id": "b5583964-a87f-4f29-91eb-e1996bb54ea4", 
    "care_recipient_id": "ad3512a6-91b1-4d7d-a005-6f8764dd0111"}',
    alert_id: null,
    task_instance_id: null,
    visit_id: '8e1dd351-9178-45d1-be2d-673692c2e6ac',
    caregiver_id: 'b5583964-a87f-4f29-91eb-e1996bb54ea4',
    payload_as_text: '{"id": "fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed", "note": "", "visit_id": 
    "8e1dd351-9178-45d1-be2d-673692c2e6ac", "timestamp": "2019-04-26T12:42:07.088Z", "volume_ml": 
    400, "event_type": "water_intake", 
    "caregiver_id": "b5583964-a87f-4f29-91eb-e1996bb54ea4", "care_recipient_id": "ad3512a6-91b1- 
    4d7d-a005-6f8764dd0111"}',
    rejected_event_id: null,
    observation_event_id: null,
    timestamp: '2019-04-26T12:42:07.088Z',    
    id: 'fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed',
    event_type: 'water_intake',       
    care_recipient_id: 'ad3512a6-91b1-4d7d-a005-6f8764dd0111'
  }

我的问题是我需要从响应中收到的多个对象中访问所有 payload 属性,并且能够从这些有效负载属性中返回属性 volume_ml ,但我似乎无法弄清楚在尝试访问该数据时出错的地方。我认为的一个可能的问题是有效负载有一个字符串作为值,我需要将其转换为 JSON 对象,所以我尝试使用 load 来做到这一点,但我不能'让它发挥作用。

I'm trying to access a nested object from an API response using axios. I will be using the data to chart a Bar Chart using ChartJS. Below is my code.

import { ChartContainer, Container } from "../styled/BarChart";
import {
  Chart as ChartJS,
  BarElement,
  LinearScale,
  CategoryScale,
} from "chart.js";
import { Bar } from "react-chartjs-2";
import { useEffect, useState } from "react";
import api from "../pages/api/posts";

ChartJS.register(BarElement, LinearScale, CategoryScale);

const BarChart = () => {
  const [chart, setChart] = useState<any[]>([]);
  const [load, setLoad] = useState<any[]>([]);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await api.get(
          "/careRecipient/ad3512a6-91b1-4d7d-a005-6f8764dd0111/events/water_intake"
        );

        setChart(response.data);
        setLoad(Object.keys(JSON.parse(response.data.payload))); //FIX
        console.log(response.data);
      } catch (err) {
        // Not in the 200 response range
        let errorMessage = "Failed!";
        if (err instanceof Error) {
          errorMessage = err.message;
        }
        console.log(errorMessage);
      }
    };

    fetchData();
  }, []);

  const data = {
    labels: chart?.map((data) => data.timestamp),
    datasets: [
      {
        label: `${chart?.length} Fluid Intake Observations`,
        data: load?.map((data) => data.volume_ml), //NOT WORKING
        backgroundColor: [
          "rgba(255, 99, 132, 0.2)",
          "rgba(54, 162, 235, 0.2)",
          "rgba(255, 206, 86, 0.2)",
          "rgba(75, 192, 192, 0.2)",
          "rgba(153, 102, 255, 0.2)",
          "rgba(255, 159, 64, 0.2)",
        ],
        borderColor: [
          "rgba(255, 99, 132, 1)",
          "rgba(54, 162, 235, 1)",
          "rgba(255, 206, 86, 1)",
          "rgba(75, 192, 192, 1)",
          "rgba(153, 102, 255, 1)",
          "rgba(255, 159, 64, 1)",
        ],
        borderWidth: 1,
      },
    ],
  };

  const options = {
    maintainAspectRatio: false,
    scales: {
      y: {
        beginAtZero: true,
      },
    },
    legend: {
      labels: {
        fontSize: 26,
      },
    },
  };

  return (
    <Container>
      <ChartContainer>
        <Bar data={data} options={options} height={400} />
      </ChartContainer>
    </Container>
  );
};

export default BarChart;

The response I am Receiving is in this format and I am receiving multiple of those:

RowDataPacket {
    payload: '{"id": "fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed", "note": "", "visit_id": "8e1dd351- 
    9178-45d1-be2d-673692c2e6ac", "timestamp": 
    "2019-04-26T12:42:07.088Z", "volume_ml": 400, 
    "event_type": "water_intake", "caregiver_id": "b5583964-a87f-4f29-91eb-e1996bb54ea4", 
    "care_recipient_id": "ad3512a6-91b1-4d7d-a005-6f8764dd0111"}',
    alert_id: null,
    task_instance_id: null,
    visit_id: '8e1dd351-9178-45d1-be2d-673692c2e6ac',
    caregiver_id: 'b5583964-a87f-4f29-91eb-e1996bb54ea4',
    payload_as_text: '{"id": "fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed", "note": "", "visit_id": 
    "8e1dd351-9178-45d1-be2d-673692c2e6ac", "timestamp": "2019-04-26T12:42:07.088Z", "volume_ml": 
    400, "event_type": "water_intake", 
    "caregiver_id": "b5583964-a87f-4f29-91eb-e1996bb54ea4", "care_recipient_id": "ad3512a6-91b1- 
    4d7d-a005-6f8764dd0111"}',
    rejected_event_id: null,
    observation_event_id: null,
    timestamp: '2019-04-26T12:42:07.088Z',    
    id: 'fc9ec0cc-d7a5-40b9-a37e-8c72616d3bed',
    event_type: 'water_intake',       
    care_recipient_id: 'ad3512a6-91b1-4d7d-a005-6f8764dd0111'
  }

My problem is that I need to access all the payload properties from the multiple objects I receive in the response and to be able to return the property volume_ml from inside those payload properties, but I can't seem to figure out where I am going wrong in trying to access that data. One possible problem I thought was the case is that payload has a string as a value and I would need to transform it to a JSON object, so I've attempted to do that using load but I couldn't get that to work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

余生再见 2025-01-21 02:18:50

事实证明,这只是我尝试访问该财产的方式中的一个愚蠢错误。我不需要负载。我所要做的就是解析地图中的有效负载属性,然后请求 .volume_ml
所以我必须完全摆脱 load 并更改它:

data: load?.map((data) => data.volume_ml), //NOT WORKING

只使用 chart ,如下所示:

data: chart?.map((data) => JSON.parse(data.payload).volume_ml)

Turned out it was just a silly mistake in the way I was trying to access that property. I didn't need load. All I had to do was parse the payload properties within the map and then ask for .volume_ml.
So I had to get rid of load entirely and change this:

data: load?.map((data) => data.volume_ml), //NOT WORKING

To using just chart like this:

data: chart?.map((data) => JSON.parse(data.payload).volume_ml)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文