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

如何使用React-query将一个API响应作为另一个API的调用参数

实现表格行图标点击时动态传入参数发起API调用

问题核心

需要让表格每行的图标被点击时,将当前行从第一个API响应中获取的codInvoicingEvent和codInvEventType作为参数,动态发起第二个API调用。当前第二个API的参数为硬编码值,需调整为支持动态参数传入。

修改方案

1. 重构第二个查询Hook,支持动态参数

将useGetViewEventDetails改为接收动态参数的自定义Hook,同时把参数加入queryKey,确保不同参数的请求能被React Query正确缓存和区分:

const useGetViewEventDetails = (params?: { codInvoicingEvent: bigint; codInvEventType: number }) => {
  return useQuery({
    queryKey: ["viewEventDetails", params?.codInvoicingEvent, params?.codInvEventType],
    queryFn: () => {
      if (!params) throw new Error("缺少查询参数");
      return getViewEventDetails(params.codInvoicingEvent, params.codInvEventType);
    },
    enabled: !!params, // 仅当参数存在时才触发请求
    staleTime: 5 * 60 * 1000, // 可选:设置缓存过期时间,优化性能
  });
};

2. 调整表格行图标点击逻辑,传入当前行参数

在组件内调用上述Hook,并修改图标点击事件,传入当前行的目标参数:

// 组件内部调用Hook
const { data: viewEventDetails, refetch: refetchViewEventDetails } = useGetViewEventDetails();

// 修改行映射函数中的图标点击逻辑
const mapTollingResponseToRows = (rows: TGetEventReconciliation[] | undefined) => {
  return rows?.map((row: TGetEventReconciliation, index: number) => {
    const icons = row.codBillingEvent && (
      <Icons 
        alt="search" 
        className="cursor-pointer" 
        height={18} 
        icon="icon-search" 
        onClick={() => {
          controller.goViewTripEvents();
          // 传入当前行的两个参数,触发第二个API查询
          refetchViewEventDetails({
            codInvoicingEvent: BigInt(row.codInvoicingEvent), // 转换为接口要求的bigint类型
            codInvEventType: row.codInvEventType // 假设row包含该字段,根据实际响应调整
          });
        }} 
      />
    );

    return {
      index,
      codInvoicingEvent: String(row.codInvoicingEvent),
      datOccurrence: row.datOccurrence,
      icons: icons,
    };
  });
};

3. 可选:处理查询状态(加载/错误)

若需在界面展示第二个API的状态,可解构对应的状态字段:

const { 
  data: viewEventDetails, 
  refetch: refetchViewEventDetails,
  isLoading: isViewEventLoading,
  isError: isViewEventError,
  error: viewEventError
} = useGetViewEventDetails();

关键注意点

  • 动态QueryKey:将参数加入queryKey,确保React Query为不同参数组合维护独立缓存,避免数据混淆。
  • 请求触发控制:通过enabled: !!params避免初始加载时的无效请求,仅在点击图标并传入参数后发起调用。
  • 类型匹配:注意codInvoicingEvent的类型转换,原代码中存储为字符串,需转回bigint以匹配接口要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 09:53:19