我不知道为什么它给的长度 undefiined
另一个是 setDailyData
不是函数
const Charts = () => {
const { setDailyData, dailyData } = useState([]);
useEffect(() => {
const fetchAPI = async () => {
setDailyData(await fetchDailyData());
};
console.log(dailyData);
fetchAPI();
}, []);
在这里,我试图从以下方面获取数据 dailyData
并使用三元操作检查是否有任何数据,然后显示图表,如果没有,(通过检查数组的长度)它应该显示 null
甚至使它 dailyData[0]
我给错误不能读取'0'属性。
const lineChart =
( dailyData.length ?(
<Line
data={{
labels: dailyData.map(({ date }) => date),
datasets: [
{
data: dailyData.map(({ confirmed }) => confirmed),
label: "Infected",
borderColor: "#3333ff",
fill: true,
},
{
data: dailyData.map(({ deaths }) => deaths),
label: "Deaths",
borderColor: "#3333ff",
backgroundColor: "rgba(255,0,0,0.5)",
fill: true,
},
],
}}
/>
):null
)
获取图表数据的API代码。
export const fetchDailyData = async ()=>{
try {
const {data} = await axios.get(`${url}/daily`);
const modifiedData = data.map((dailyData) =>({
confirmed:dailyData.confirmed.total,
deaths:dailyData.deaths.total,
date:dailyData.reportDate
}));
console.log(data);
return modifiedData;
} catch (error) {
return error;
}
}
useState返回一个数组,而不是一个对象
根据你的代码
const Charts = () => {
// const { setDailyData, dailyData } = useState([]);
const [dailyData, setDailyData] = useState([]) // <-- change to this
useEffect(() => {
const fetchAPI = async () => {
setDailyData(await fetchDailyData());
};
console.log(dailyData);
fetchAPI();
}, []);