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

React项目无法获取public文件夹下本地JSON文件问题求助

你遇到的问题本质是fetch回调的语法错误:当箭头函数用花括号包裹执行逻辑时,必须显式使用return返回值,你原代码中response.json()的结果没有被返回,导致下一个then接收的data为undefined,自然无法正常解析。

修正方案

1 直接修改原有then链写法

两种修正方式二选一即可:

const getResponse = () => {
  fetch('/responseScript.json')
    // 方式1:去掉花括号,箭头函数直接返回表达式结果
    .then(response => response.json())
    // 方式2:保留花括号,显式加return
    // .then(response => { return response.json() })
    .then(data => { console.log(data) })
    .catch(err => console.error('请求错误:', err))
}

useEffect(() => {
  getResponse();
}, []); // 空依赖数组保证只在组件挂载时执行一次

2 更易读的async/await写法

const getResponse = async () => {
  try {
    const response = await fetch('/responseScript.json');
    const data = await response.json();
    console.log(data);
  } catch (err) {
    console.error('获取JSON失败:', err);
  }
}

useEffect(() => {
  getResponse();
}, []);

其他注意事项

  • 路径开头加/可以确保始终从站点根目录(对应public文件夹)定位资源,避免当前页面路由为多级路径时,相对路径寻址出错
  • TypeScript场景下可以提前定义JSON数据结构,获得类型提示:
interface IResponseItem {
  Category: string;
  Issue: string;
  Answer: string;
  Response: string;
}

// 解析时指定类型
const data = await response.json() as IResponseItem[];
  • 如果你不需要动态读取JSON内容,也可以直接导入JSON文件使用,无需fetch:
    • Create React App项目:
    import responseData from '../public/responseScript.json';
    
    • Vite项目:
    import responseData from '../public/responseScript.json' assert { type: 'json' };
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 10:15:00