我有一个schedules.ts
文件,我有一个功能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)
})
}
在我的 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;
但是当我去组件时,我得到了
Tab1.tsx:38 Uncaught TypeError: Cannot read property 'map' of undefined
我是新来的反应和这个打字稿的事情。我希望我可以v-for
在 vue.js 中使用like。有人可以告诉我这是什么问题,我该如何解决?谢谢..
事实证明,问题是data
从 API 返回没有schedules
属性,因此setSchedules(data.schedules)
使schedules
undefined
. 数据作为一个整体已经是所需的数组,因此需要调用setSchedules
withdata
作为参数。
也就是说,身体useEffect
应该是
getSchedules().then(data => setSchedules(data));
如果您愿意,可以将其简化为
getSchedules().then(setSchedules);
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句