React请求Spring Boot接口卡顿在Loading状态排查求助
React请求后端数据一直卡在Loading状态的排查与解决
我是React新手,跟着一套有点过时的YouTube教程学习,现在碰到个问题:Spring Boot后端跑在8080端口,React项目在VS Code里搭建,已经配置了代理连接后端,但页面一直显示'Loading',拿不到分类数据。
相关代码
Category.js
import React, { Component } from 'react'; class Category extends Component { state = { isLoading: true, Categories: [] } async componentDidMount() { const response = await fetch('/api/categories'); const body = await response.json(); this.setState({ Categories: body, isLoading: false }); } render() { const { Categories, isLoading } = this.state; if (isLoading) return (<div>Loading......</div>); return ( <div> <h2>Categories</h2> { Categories.map(category => <div id={category.id}> {category.name} </div> ) } </div> ); } } export default Category;
index.js
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import Category from './Category'; import reportWebVitals from './reportWebVitals'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <Category/> </React.StrictMode> ); reportWebVitals();
开发者工具截图

排查与解决步骤
1. 确认代理配置有效性
React项目的代理配置需在package.json中添加:
"proxy": "http://localhost:8080"
添加后必须重启React开发服务器,否则配置不生效。
2. 检查网络请求状态
打开浏览器开发者工具的「Network」标签,找到/api/categories请求:
- 若状态码为404:核对Spring Boot后端的接口路径是否为
/api/categories,同时确认后端是否配置了跨域支持(即使使用代理,后端的跨域拦截也可能导致请求失败)。 - 若状态码为500:查看Spring Boot的后端日志,排查接口内部报错。
- 若请求未发送:在
componentDidMount中添加console.log('开始请求数据'),确认该方法是否被执行。
3. 增加错误处理逻辑
原代码未处理请求失败的情况,一旦请求报错,isLoading会一直保持true,导致页面卡在加载状态。修改componentDidMount:
async componentDidMount() { try { const response = await fetch('/api/categories'); // 检查请求是否成功 if (!response.ok) { throw new Error(`请求失败: ${response.status}`); } const body = await response.json(); this.setState({ Categories: body, isLoading: false }); } catch (error) { console.error('获取分类数据失败:', error); // 失败时也要结束加载状态,避免一直卡在Loading this.setState({ isLoading: false }); } }
4. 核对后端返回数据格式
确保后端返回的是数组格式(比如[{"id":1,"name":"分类1"},...])。如果后端返回的是包含数组的对象(比如{"data": [...], "code": 200}),则需要修改代码为:
const body = await response.json(); this.setState({ Categories: body.data, isLoading: false });
5. 测试React StrictMode影响
React 18的StrictMode会让componentDidMount执行两次,但通常不影响最终状态。如果怀疑是这个问题,可以暂时去掉StrictMode测试:
root.render( <Category/> );
内容的提问来源于stack exchange,提问作者user24209788
相关产品推荐
相关产品推荐

