【发布时间】:2020-09-25 19:13:45
【问题描述】:
我正在开发一个 react-native/nodeJS 项目,但我遇到了使用 async/await 函数对我的后端进行 Axios API 调用的问题。
代码如下:
const TimeTable = () => {
const [attendedCourses, setAttendedCourses] = useState([]);
const [courseSchedules, setCourseSchedules] = useState([]);
useEffect(() => {
getUserCourses();
getCourseSchedule();
console.log(courseSchedules);
}, []);
const getCourseSchedule = async () => {
for (const item of attendedCourses) {
try {
const res = await axios.get(`/api/lesson/findById/${item.courseId}`);
setCourseSchedules((prev) => [
...prev,
{
id: res.data._id,
name: res.data.name,
schedule: [...res.data.schedule],
},
]);
} catch (err) {
const error = err.response.data.msg;
console.log(error);
}
}
};
const getUserCourses = async () => {
const userId = "12345678"; //hardcoded for testing purpose
try {
const res = await axios.get(`/api/users/lessons/${userId}`);
setAttendedCourses(res.data);
} catch (err) {
const error = err.response.data.msg;
console.log(error);
}
};
return (...); //not important
};
export default TimeTable;
getUserCourses() 方法行为正确并始终返回一个对象数组,该数组保存在attendedCourses 状态。第二种方法getCourseSchedule() 不能正常工作。 useEffect() 中的 console.log() 大部分时间打印一个空数组。
有人可以向我解释为什么吗?谢谢!
【问题讨论】:
-
因为您在收到服务器的任何响应之前就记录了该值。
-
试试
await getUserCourses()和await getCourseSchedule()
标签: javascript async-await axios