【发布时间】:2021-05-31 11:38:10
【问题描述】:
我正在尝试使用 useEffect 和 useState 在组件中进行许多 HTTP 调用,以存储此 http 调用的结果。我以为我对 useEffect 的工作原理有了基本的了解,但我很困惑为什么我的代码不起作用,因此一定是错误地实现了它。
这是我的仪表板组件中的 useEffect 挂钩代码:
useEffect(() => {
isMounted.current = true;
const fetchData = async () => {
if (survey === null) {
const surveyResponse = await getSurveys('standard');
setSurvey(surveyResponse.data);
}
if (teamInfo === null) {
const teamInfoResponse = await getTeamInfo(user.teamId);
setTeamInfo(teamInfoResponse.data);
}
if (week === null || year === null) {
const weekAndYearResponse = await getWeekAndYear();
setWeek(weekAndYearResponse.data.weekNumber);
setYear(weekAndYearResponse.data.year);
}
if (week && year && !stats) {
const statsResponse = await getTeamSurveyStats(week, year, user.teamId);
setStats(statsResponse.data);
}
};
fetchData();
return () => {
// executed when unmount
isMounted.current = false;
};
}, [survey, teamInfo, week, year, stats, user.teamId]);
我认为检查我是否为每个调用的返回设置的状态值,我可以将这个 http 调用放入一个条件中,如果该变量为空,它只会在重新渲染时发出 http 请求,正如我使用 useState(null) 定义的那样。
当我检查我的网络标签时,我看到以下内容:
第一次调用只运行一次,这是正确的 - 这是 getSurveys 第二个调用运行两次,这是不正确的,因为只需要运行一次 - 这是 getTeamInfo 第三次调用运行 5 次,这很奇怪,因为只需要运行一次 - 这是 getWeekAndYear 第四个调用只运行一次,这是正确的。
谁能明白为什么其中 2 个调用会运行多次? 谢谢
【问题讨论】:
标签: reactjs http use-effect