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

添加React Query后React+TypeScript项目页面内容消失求助

解决React Query导致页面空白的问题

问题根源

你的代码里有两个关键错误引发了页面崩溃:

  • useQuery回调未返回Promise
    useQuery要求第二个参数必须是返回Promise的函数,你的回调里只执行了axios.get但没有返回结果,也没在then里返回数据,导致React Query无法处理异步逻辑,触发错误。

  • 无效的API请求地址
    axios.get("")是空地址,会直接触发网络错误,未处理的错误会导致组件渲染失败,页面空白。

修正方案

1. 修复useQuery回调

确保回调返回Promise和请求数据:

() => axios.get("你的实际API地址").then(response => {
  console.log(response.data);
  return response.data; // 必须返回数据给React Query
})

2. 替换为有效API地址

把空的请求地址换成实际可用的接口,比如你要获取meme图的公开API。

3. 增加状态处理(可选但推荐)

捕获加载、错误状态,避免页面直接崩溃:

import { useQuery } from "@tanstack/react-query";
import axios from "axios";

export const Body = () => {
  // 替换为实际可用的API地址
  const API_URL = "https://api.example.com/memes";

  const { data: meme = {}, status, error } = useQuery(["id"], () => {
    return axios.get(API_URL).then((response) => {
      console.log(response.data);
      return response.data;
    });
  });

  const defaultImage =
    "https://i.pinimg.com/originals/0a/bb/e5/0abbe546e479edc1eb62f5a8ccd66328.jpg";

  // 错误状态提示
  if (status === 'error') {
    return <div className="body__container">加载失败: {error?.message}</div>;
  }

  // 加载状态提示
  if (status === 'loading') {
    return <div className="body__container">加载中...</div>;
  }

  return (
    <div className="body__container">
      <main>
        <div className="input__container">
          <input placeholder="First text" />
          <input placeholder="second text" />
        </div>
        <button> Get new image 🏞</button>
        <img src={defaultImage} height="400px" width="400px" />
      </main>
    </div>
  );
};

验证步骤

  1. 替换API_URL为真实可用的接口
  2. 重启开发服务器
  3. 查看控制台是否还有错误,页面是否正常渲染

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:25:32