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

React应用从Node.js API获取数据已到浏览器但页面不显示

问题分析与解决方案

核心问题

你的代码存在两个关键错误导致数据无法渲染:

  1. 错误存储响应数据:Axios返回的res是完整响应对象,后端返回的实际数据在res.data属性中。你直接将整个res对象存入post状态,而res并非数组,导致post?.length > 0始终为false,页面一直显示加载状态。
  2. 冗余请求调用:useEffect中同时调用了fetch和axios.get,既多余又可能引发重复请求。

修正后的代码

import './CSS_PSI.css'
import logout from './logout.ico';
import { Link } from 'react-router-dom';
import axios from 'axios';
import { useState, useEffect } from 'react';

function Projetos() {
  const [post, setPost] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 移除冗余的fetch调用,仅保留axios请求
    axios.get("/projeto/all")
      .then((res) => {
        // 存储后端返回的实际数据res.data
        setPost(res.data);
      })
      .catch((err) => {
        // 添加错误处理,方便排查问题
        setError(err.message);
      })
      .finally(() => {
        // 请求完成后结束加载状态
        setLoading(false);
      });
  }, []);

  // 调试时打印最新的post数据
  useEffect(() => {
    console.log("当前post数据:", post);
  }, [post]);

  if (loading) return <div className="title">Data Loading.. </div>;
  if (error) return <div className="title">加载失败: {error}</div>;

  return (
    <div className="App">
      {post.length > 0 ? (
        post.map((value, key) => (
          <div key={key} className="post"> {/* 给map元素添加唯一key */}
            <div className="title"> {value.titulo} </div>
            <div className="body">{value.regras}</div>
          </div>
        ))
      ) : (
        <div className="title">暂无数据</div>
      )}
    </div>
  );
}

export default Projetos;

额外优化说明

  • 新增loading和error状态,提升用户体验同时便于排查问题
  • 给map遍历的元素添加key属性,符合React渲染规范
  • 将调试用的console.log放到依赖post的useEffect中,确保打印最新状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 21:10:28