我正在嘗試在 recharts linechart 中使用從 api 獲取的資料,但我在映射 json 資料時遇到了問題。我有一個回傳資料的 api,如下所示,基本上是每個月的預測計數,如果月份不存在則為 0,但資料的格式我無法通過它進行映射。我在 json 資料中有一個物件,想將它轉換為多個物件,使用鍵作為另一個鍵的值,使用值作為另一個鍵的另一個值。抱歉我的錯誤解釋我不知道如何描述這個問題。
資料格式
[
{
"_id": 2022,
"jan": 1,
"feb": 0,
"mar": 0,
"apr": 0,
"may": 0,
"jun": 0,
"jul": 0,
"aug": 0,
"sep": 0,
"oct": 0,
"nov": 13,
"dec": 0
}
]
我想要在某種狀態下使用的格式
[
{
"month": "jan",
"count": 1
},
{
"month":"feb",
"count":"0"
},
{
"month":"mar",
"count":"0"
}
{
"month":"apr",
"count":"0"
},
{
"month":"may",
"count":"0"
}
}
我也想跳過這一年
線圖代碼
import React, { useEffect, useState } from "react";
import {
LineChart,
XAxis,
YAxis,
CartesianGrid,
Line,
Tooltip,
Legend
} from 'recharts';
const PredictionsMonthLinechart = () => {
const [d, setD] = useState([
{
month: 'jan',
predictions: 4000,
},
])
const fetchData = async () => {
const res = await fetch("http://localhost:5000/query/predictions_per_month");
const data = await res.json()
.then(data => {
setD((Object.keys(data)).map((key) => {
return {
month: key,
predictions: data[key]
}
}))
})
console.log(data);
console.log(d);
}
useEffect(() => {
fetchData();
}, []);
return (
<LineChart width={1100} height={400} data={d}
margin={{ top: 5, right: 30, left: 20, bottom: 5 }}>
<CartesianGrid strokeDasharray="3 3" />
<XAxis dataKey="month" />
<YAxis />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="predictions" stroke="#8884d8" />
</LineChart>
)
}
export default PredictionsMonthLinechart;
我試過使用 Object.entries() 但它一直在 IDE 中給我錯誤 Object.keys() 回傳未定義的物件但至少它正確讀取鍵。
Uncaught Error: Objects are not valid as a React child (found: object with keys {\_id, jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec}). If you meant to render a collection of children, use an array instead.
uj5u.com熱心網友回復:
假設data您從請求中得到的是(如您所說):
[
{
"_id": 2022,
"jan": 1,
"feb": 0,
"mar": 0,
"apr": 0,
"may": 0,
"jun": 0,
"jul": 0,
"aug": 0,
"sep": 0,
"oct": 0,
"nov": 13,
"dec": 0
}
]
那么這一行是不正確的,因為data它是一個陣列,而不是一個物件:
setD((Object.keys(data)).map((key) => {
將代碼改編成這樣應該可以編譯(它還包含一個filterfor the year 屬性):
.then(data => {
setD((Object.keys(data[0])).filter(key => key !== "_id").map((key) => {
return {
month: key,
predictions: data[0][key]
}
}))
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/534235.html
標籤:反应打字稿反应打字稿
