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

使用多个useQuery获取不同学生数据却返回相同结果的问题求助

问题:重复调用useQueryStudent获取不同学生数据返回相同结果

我用两个useQueryStudent钩子获取不同学生的数据:

const {isLoading, error, data} = useQueryStudent(id_x);
const {isLoading: isLoading2, error: error2, data: data2} = useQueryStudent(id_y)

但data和data2都返回了student(id_x)的相同数据,尝试封装成函数调用也没用:

const queryMultiple = () => {
    const res1 = useQueryStudent(id_x)
    const res2 = useQueryStudent(id_y)

    return [res1, res2]
  }

const [
    { isLoading: isLoading1,
      error: error1,
      data: data1, },
    { isLoading: isLoading2,
      error: error2,
      data: data2, }
] = queryMultiple()

我的useQueryStudent实现代码如下:

function useQueryStudent(studentId) {
  const queryKey = ["student"];
  const { token, updateToken } = useStoreToken();

  const getStudent = async () => {
    try {
      const headers = { Authorization: `Bearer ${token}` };
      const endpoint = `${BASE_URL}/api/student/${studentId}`;
      const res = await axios.get(endpoint, { headers });
      const { message, data, token: newToken } = res.data;
      debug({ message, data });
      updateToken(newToken);
      return data;
    } catch (err) {
      debug({ err });
      showNotification({
        title: "Oh no!",
        message: getMessage(err),
        color: "red",
        icon: <TbX />,
      });
      throw err;
    }
  };

  return {
    ...useQuery(queryKey, getStudent, {
      fetchPolicy: "no-cache",
    }),
  };
}

另外我还用useEffect更新状态:

useEffect(() => {
  if (data1) {
    setStudentAData(data1);
  }
}, [data1]);

useEffect(() => {
    if (data2) {
      setPlayerBData(data2);
    }
}, [data2]);

原因与解决方案

问题核心在于React Query的queryKey不唯一:React Query靠queryKey识别不同的查询缓存,你现在的queryKey是固定的["student"],不管传哪个studentId,它都会判定这是同一个查询,直接复用之前的缓存结果,所以两次调用返回了相同数据。

怎么改:

  1. 给queryKey加上studentId:
    把studentId加入queryKey的数组里,让每个学生的查询都有独一无二的标识:

    const queryKey = ["student", studentId]; // 关键修改点
    
  2. 无需额外调整getStudent:
    你的getStudent函数已经用到了studentId,只要queryKey包含了这个参数,React Query会自动在studentId变化时触发新查询,不用额外处理依赖。

修改后的完整useQueryStudent代码:

function useQueryStudent(studentId) {
  const queryKey = ["student", studentId]; // 加入studentId保证唯一性
  const { token, updateToken } = useStoreToken();

  const getStudent = async () => {
    try {
      const headers = { Authorization: `Bearer ${token}` };
      const endpoint = `${BASE_URL}/api/student/${studentId}`;
      const res = await axios.get(endpoint, { headers });
      const { message, data, token: newToken } = res.data;
      debug({ message, data });
      updateToken(newToken);
      return data;
    } catch (err) {
      debug({ err });
      showNotification({
        title: "Oh no!",
        message: getMessage(err),
        color: "red",
        icon: <TbX />,
      });
      throw err;
    }
  };

  return {
    ...useQuery(queryKey, getStudent, {
      fetchPolicy: "no-cache",
    }),
  };
}

额外提示:

  • 没必要封装queryMultiple函数,直接在组件顶层调用两次useQueryStudent就行,React允许组件里调用多个自定义Hook。
  • fetchPolicy: "no-cache"可以保留,但只要queryKey唯一,就算用默认缓存策略,也能正确区分不同学生的数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 21:27:54