You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中.map()内调用异步查询函数仅首个条目生效问题求助

代码存在的3个核心问题

  • 异步逻辑错误:axios.get是异步方法,GuideAssigned函数不会等待接口返回就会直接执行return guide,返回的永远是函数调用瞬间的guide状态值,不是当前tourId对应的查询结果。
  • 状态共用导致覆盖:所有行的GuideAssigned调用共享同一个guide状态,每个请求返回后都会覆盖这个状态的取值,最终所有行只会显示最后一次请求的结果,而非每行对应tourId的结果。
  • 渲染逻辑不合理:在map渲染回调中直接发起请求,每次组件重渲染都会触发全量重复请求,会造成严重的性能浪费。

修复方案

提前在useEffect中批量查询所有行程对应的导游信息,存储为键值对映射后再渲染:

  1. 定义存储导游映射的状态,在bookings更新时批量请求数据:
import { useState, useEffect } from 'react';
import axios from 'axios';

// 组件内代码
const [guideMap, setGuideMap] = useState({});

useEffect(() => {
  const fetchAllGuides = async () => {
    const tempMap = {};
    // 对tourId去重,避免同一个行程重复请求
    const uniqueTourIds = [...new Set(bookings.map(item => item.tourId))];
    for (const tid of uniqueTourIds) {
      try {
        const res = await axios.get(`http://localhost:8070/assignedGuides/get/${tid}`);
        tempMap[tid] = res.data.guideId || 'Not Assigned';
      } catch (err) {
        console.error(err);
        tempMap[tid] = 'Not Assigned';
      }
    }
    setGuideMap(tempMap);
  };
  if (bookings.length) fetchAllGuides();
}, [bookings]);
  1. 修改表格渲染逻辑,直接从映射中取值:
{bookings.map((booking, index) => (
  // 必须给遍历元素加唯一key,避免React渲染异常
  <tr key={booking.tourId}>
    <th scope="row">{index + 1}</th>
    <td>{booking.tourId}</td>
    <td>{booking.bookingDate}</td>
    <td>{booking.arrivalDate}</td>
    <td>{booking.country}</td>
    <td>{guideMap[booking.tourId] ?? 'Loading...'}</td>
    <td>
      <Button 
        color="warning" 
        style={{padding: "5px", width: "80px", marginBottom: "8px"}}
        onClick={() => history.push(`/assign-guide/${booking.username}`)}
      >
        Assign Guide
      </Button>
    </td>
  </tr>
))}

内容的提问来源于stack exchange,提问作者Shehan Silva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:48:01