我正在学习 React 并试图理解我做错了什么。
我在 main.py 中有一个像这样的端点:
def get_db_data():
engine = create_engine(config.get('database', 'con'))
table = 'raw_data'
df = pd.read_sql(table, engine)
return df
@app.get("/rawdata", tags=['data'], status_code=200)
async def raw_data():
data = get_db_data()
return data.to_dict()
为了简洁起见,它呈现了一个 Pandas Dataframe,我将其转换为字典,如下所示:
Object
Date: {0: '2019-01', 1: '2019-02', 2: '2019-03', 3:
'2019-04', 4: '2019-05'}
Sales:{0: 71, 1: 67, 2: 84, 3: 65, 4: 78 }
[[Prototype]]: Object
然后在 App.js 中,我有这个:
import './App.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Plot from "react-plotly.js";
function App() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('/rawdata').then((response) => {
console.log(response.data)
setData(response.data);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
}, []);
return (
<Plot
data={[
{
x: data.map((point) => point.Date),
y: data.map((point) => point.Sales),
type: "scatter",
mode: "lines+points",
marker: { color: "blue" },
},
]}
layout={{ width: 800, height: 400, title: "Time Series Plot" }}
/>
);
}
export default App;
控制台正在“查看”来自端点的 JSON 数据,但我收到以下错误: x: data.map((point) => point.Date), y: data.map((point) => point.Sales),
“data.map 不是一个函数 类型错误:data.map 不是函数”
谁能告诉我我做错了什么?
因为您收到的回复为
object
。因此,如果想在 map
中传递 array
,array
函数仅适用于 x
,并且 y
键只需使用 Object.values
它将从对象(键/值对)生成 array
。
我应用了一些最佳实践,例如显示加载
import './App.css';
import React, { useEffect, useState } from 'react';
import axios from 'axios';
import Plot from "react-plotly.js";
function App() {
const [data, setData] = useState({});
const [isLoaded, setLoaded] = useState(false);
useEffect(() => {
axios.get('/rawdata').then((response) => {
console.log(response.data)
setData(response.data); // react will batch this two state updated into to one
setLoaded(true);
})
.catch((error) => {
console.error('Error fetching data:', error);
});
}, []);
if(!isLoaded){ // your loading component
return (
<div>
Loading...
</div>
)
}
return (
<Plot
data={[
{
x: Object.values(data.Date),
y: Object.values(data.Sales),
type: "scatter",
mode: "lines+points",
marker: { color: "blue" },
},
]}
layout={{ width: 800, height: 400, title: "Time Series Plot" }}
/>
);
}
export default App;