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

React中使用useEffect Hook获取本地JSON数据报错求助

解决React项目中fetch同目录db.json失败的问题

问题场景

在React项目的landing-page.jsx文件中,使用useEffect结合fetch方法获取同目录下的db.json文件数据时操作失败,控制台出现报错。

原组件代码

import "./landing-page.css";
import { useState, useEffect } from "react";

export default function Landing_page() {
const [data, set_data] = useState(null);
useEffect(() => {
    fetch("./db.json")
        .then((res) => res.json())
        .then((d) => console.log(d));
}, []);

db.json内容

{
"projects": [
    {
        "id": 1,
        "name": "Lorem ipsum dolor sit",
        "level_name": "newbie",
        "level_number": "1",
        "description": "Fugiat quibusdam tempore explicabo earum perferendis, pariatur dolores. Vitae perspiciatis officia nobis?",
        "preview_link": "https://google.com",
        "github_link": "https://google.com"
    }
]
}

解决方案

1. 修正文件路径与资源存放位置

React项目中,fetch的请求路径是相对于打包后的静态资源根目录,而非组件文件的相对路径。默认情况下,组件目录下的db.json不会被识别为可访问的静态资源。

  • 将db.json移动到项目根目录的public文件夹下(若没有public目录则新建)。
  • 修改fetch路径为根路径:fetch("/db.json")。

2. 添加错误捕获逻辑

原代码未处理请求失败或解析错误的情况,无法定位具体问题。添加错误捕获可以明确报错原因:

useEffect(() => {
  fetch("/db.json")
    .then((res) => {
      // 检查响应状态是否正常
      if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`);
      return res.json();
    })
    .then((d) => {
      console.log(d);
      set_data(d); // 记得更新状态变量
    })
    .catch((err) => console.error("获取数据出错:", err));
}, []);

3. 验证开发服务器配置

使用Create React App等脚手架创建的项目,public目录下的文件会自动被作为静态资源服务。确保开发服务器正常启动,没有自定义路径配置干扰静态资源访问。

修改后的完整组件代码

import "./landing-page.css";
import { useState, useEffect } from "react";

export default function Landing_page() {
  const [data, set_data] = useState(null);

  useEffect(() => {
    fetch("/db.json")
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP错误!状态码:${res.status}`);
        return res.json();
      })
      .then((d) => {
        console.log(d);
        set_data(d);
      })
      .catch((error) => {
        console.error("获取数据失败:", error);
      });
  }, []);

  return (
    <div className="landing-page">
      {/* 示例渲染数据 */}
      {data && data.projects.map(project => (
        <div key={project.id} className="project-card">
          <h3>{project.name}</h3>
          <p className="level">等级:{project.level_name} ({project.level_number})</p>
          <p>{project.description}</p>
        </div>
      ))}
    </div>
  );
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 23:24:37