首页 > 解决方案 > useEffect fetch 不从本地 db.json 检索数据

问题描述

我试图通过使用 db.json 文件(相对路径:src\plant-api\db.json)来模拟 Plant API,并将其从父组件(ItemList)传递给它的子组件(Item),但它不起作用,因为即使我可以在我的 console.log 中看到它,我也看不到屏幕上显示任何数据。这是完整的代码

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

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

  useEffect(() => {
    fetch(Data)
      .then((response) => response.json())
      .then((data) => setPlants(data));
  }, []);

  console.log(Data)

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

export default ItemList;
import React from "react";
import ItemCount from "./ItemCount";

const Item = ({ data }) => {
  return (
    <div>
      <div className="item">
        <img src={data.pic} alt="plant-image" />
        <h3>{data.name}</h3>
        <p>{data.category}</p>
        <h4>{data.price}</h4>
        <ItemCount stock="10" initial="0" />
      </div>
    </div>
  );
};

export default Item;

目录结构

任何帮助都是需要和感激的!

标签: javascriptreactjsapifetch

解决方案


也许你可以使用 json-server 包,这样你就可以创建一个虚拟 API。

在终端中使用如下代码的示例,请确保代码在 db.json 文件目录中运行。

npx json-server db.json -p2000

稍后将有一个 json 服务器作为 API 在端口 2000 上运行


推荐阅读