我得到了一个 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: 无法读取未定义的属性“map”
我是 react 和 typescript 的新手。我希望我可以像在 vue.js 中一样使用 v-for
。有人可以告诉我这是什么问题以及如何解决吗?谢谢..
最佳答案
问题原来是从 API 返回的 data
没有 schedules
属性,因此 setSchedules(data.schedules)
正在制定时间表
未定义
。整个数据已经是所需的数组,因此需要以 data
作为参数调用 setSchedules
。
也就是说,useEffect
的主体应该是
getSchedules().then(data => setSchedules(data));
如果您愿意,可以简化为
getSchedules().then(setSchedules);
关于javascript - ReactJS使用Ionic Uncaught TypeError : Cannot read property 'map' of undefined from axios request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437897/