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

React项目useEffect调用fetch无法从本地db.json获取数据求助

问题根源

你混淆了本地JSON文件的两种使用方式:

  • 直接import导入JSON时,构建工具会直接将JSON内容解析为JS对象赋值给导入的变量,不需要再用fetch请求
  • 你当前给fetch传入了已经解析好的JS对象,而非资源路径,因此无法得到正确的返回结果,plants状态始终为空数组,导致页面没有渲染内容。

解决方法(二选一即可)

方案1:直接使用导入的JSON内容(无需模拟请求流程时用)

删除useEffect的请求逻辑,直接用导入的Data赋值给状态即可,修改后ItemList代码如下:

import React, { useState } from "react";
import Item from "./Item";
import Data from "../plant-api/db.json"

const ItemList = () => {
  // 直接用导入的JSON初始化状态
  const [plants, setPlants] = useState(Data);

  return (
    <div className="items">
      {plants.map((plant, index) => {
        // 建议给遍历项加上唯一key,避免React警告,有业务id优先用id
        return (
          <div key={plant.id ?? index}>
            <Item data={plant} />
          </div>
        );
      })}
    </div>
  );
};

export default ItemList;

方案2:保留fetch模拟API请求的流程

  1. 将src/plant-api/db.json文件移动到项目public目录下,保持路径为public/plant-api/db.json
  2. 删除import Data from "../plant-api/db.json"这行导入语句
  3. 修改useEffect内的fetch路径为静态资源路径,修改后代码如下:
import React, { useState, useEffect } from "react";
import Item from "./Item";

const ItemList = () => {
  const [plants, setPlants] = useState([]);

  useEffect(() => {
    // 请求public目录下的静态资源
    fetch("/plant-api/db.json")
      .then((response) => response.json())
      .then((data) => setPlants(data))
      // 建议加错误捕获方便排查问题
      .catch(err => console.log("请求错误:", err));
  }, []);

  return (
    <div className="items">
      {plants.map((plant, index) => {
        return (
          <div key={plant.id ?? index}>
            <Item data={plant} />
          </div>
        );
      })}
    </div>
  );
};

export default ItemList;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:57:02