javascript - 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;
任何帮助都是需要和感激的!
解决方案
也许你可以使用 json-server 包,这样你就可以创建一个虚拟 API。
在终端中使用如下代码的示例,请确保代码在 db.json 文件目录中运行。
npx json-server db.json -p2000
稍后将有一个 json 服务器作为 API 在端口 2000 上运行
推荐阅读
- javascript - JavaScript:Fullcalendar - 在月份之间插入中断/空行
- powershell - PowerShell 根据大写字母标准更新注册表值
- php - 如何在 php 中为 Wordpress 查询多个 SQL 任务?
- git - Git 日志 - 在不相关的历史记录之间添加分隔符,尤其是 --oneline
- angular - 如何修复角度获取请求中的“确定”消息
- jsp - 我们想为 JSP 页面的 i18n 使用 JSTL FMT 标签,但将语言代码文件夹保留在 url 中以用于 SEO 目的
- mysql - 如何快速在 MySQL 中的多个列中进行全文搜索?
- regex - 在 powershell 脚本中使用正则表达式替换键/值标签的值
- excel - 根据另一列中的值提取唯一值以分隔工作表
- c - 编译器不正确的注册表 %rax C 代码问题