React中useEffect无限执行导致系统变慢问题排查求助
问题根源
- 负责拉取booking列表的useEffect未配置依赖数组,组件每次渲染都会重新发起请求,调用
setBookings后会生成新的数组引用,触发依赖bookings的第二个useEffect执行,形成无限渲染循环。 - 拉取guideId的逻辑未做去重,每次触发useEffect都会为所有tourId重复发起请求,产生大量冗余请求。
修复方案
第一步:修复拉取booking列表的useEffect
给该useEffect添加空依赖数组,仅在组件首次挂载时拉取一次booking数据:
useEffect(()=>{ axios.get("http://localhost:8070/bookings/").then((res) =>{ setBookings(res.data); }) }, []); // 新增空依赖数组
第二步:优化guideId拉取逻辑
新增去重判断,仅为未查询过guide信息的tourId发起请求,避免重复查询:
useEffect(() => { if(bookings.length === 0) return; // 过滤已经查询过guide信息的tourId,无需重复请求 const needFetchTourIds = bookings .map(item => item.tourId) .filter(tourId => !guides.hasOwnProperty(tourId)); needFetchTourIds.forEach(tourId => { axios.get(`http://localhost:8070/assignedGuides/check/${tourId}`).then((res) =>{ if(res.data === true){ axios.get(`http://localhost:8070/assignedGuides/get/${tourId}`) .then(res => { setGuides(prevGuides => ({ ...prevGuides, [tourId]: res.data.guideId, })); }) } else { // 未分配导游的tourId也标记为已查询,避免下次重复请求 setGuides(prevGuides => ({ ...prevGuides, [tourId]: null })) } }) }); },[bookings, guides]); // 新增guides依赖
第三步:优化序号生成逻辑
移除全局的number变量,直接用map的索引生成序号,避免每次渲染重置计数的问题:
{bookings.map((booking, index) =>( <tr> <th scope = "row">{index + 1}</th> {/* 其余代码保持不变 */} ))}
内容的提问来源于stack exchange,提问作者Shehan Silva
相关产品推荐
相关产品推荐

