获取有关的错误:无法读取未定义的属性“长度”
2020-05-11
147
我不知道为什么它给出的长度是
未定义
,而另一个是
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;
}
}
1个回答
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();
}, []);
pepe_witch
2020-05-11