[英]ReactJS using Ionic Uncaught TypeError: Cannot read property 'map' of undefined from axios request
I got a schedules.ts
file and I got a function getSchedules()
我有一个schedules.ts
文件,我有一个 function getSchedules()
import axios from 'axios'
export default function getSchedules(){
const config = {
headers: { Authorization: 'Bearer ' + localStorage.getItem('bearer_token') ,
Accept: 'application/json',
'Content-Type': 'application/json',
}
};
return axios.get('http://127.0.0.1:8000/api/auth/getSchedules',config).
then((res)=>{
return res.data
}).catch((err)=>{
console.log(err)
})
}
In my Tab1 component, I want to get the data from my axios request and display by using array.map在我的 Tab1 组件中,我想从我的 axios 请求中获取数据并使用 array.map 显示
import getSchedules from '../methods/schedules'
const Tab1: React.FC = () => {
const [schedules, setSchedules] = React.useState([]);
React.useEffect(() => {
getSchedules().then(data => setSchedules(data.schedules));
}, []);
return (
<IonPage>
<IonHeader>
<IonToolbar>
<IonTitle>Appointments</IonTitle>
</IonToolbar>
</IonHeader>
<IonContent className="ion-padding">
<IonList>
{schedules.map(elem => {
return(
<IonItem key={elem['id']}>
<IonLabel>
<h2>{elem['schedule_type']}</h2>
<h3>{elem['type']}</h3>
<h3>{elem['start_date']}</h3>
</IonLabel>
</IonItem>
)
})}
</IonList>
</IonContent>
</IonPage>
);
};
export default Tab1;
But when I go to the component I got但是当我 go 到我得到的组件时
Tab1.tsx:38 Uncaught TypeError: Cannot read property 'map' of undefined
I am new to react and this typescript thing.我是新来的反应和这个 typescript 的事情。 I wish i can use v-for
like in vue.js.我希望我可以在 vue.js 中使用v-for
。 Can someone tell me what is the problem of this and how can I solve?有人可以告诉我这是什么问题,我该如何解决? Thanks..谢谢..
The problem turned out to be that the data
coming back from the API had no schedules
property, so setSchedules(data.schedules)
is making schedules
undefined
.问题原来是从 API 返回的data
没有schedules
属性,因此setSchedules(data.schedules)
正在使schedules
undefined
。 The data as a whole is already the desired array, so what is needed is to call setSchedules
with data
as the argument.数据作为一个整体已经是想要的数组了,所以需要调用setSchedules
,以data
为参数。
That is, the body of useEffect
should be也就是说, useEffect
的主体应该是
getSchedules().then(data => setSchedules(data));
which can, if you prefer, be simplified as如果您愿意,可以将其简化为
getSchedules().then(setSchedules);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.