从公用文件夹ReactJS获取本地JSON文件

编程入门 行业动态 更新时间:2024-10-24 00:21:00
本文介绍了从公用文件夹ReactJS获取本地JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有两天的问题;我希望在使用react-app创建的React应用程序中从我的公共文件夹中读取本地JSON。

I have a problem since two days; I want read a local JSON from my public folder on my React application created with react-app.

这是我的项目结构:

  • 公开

  • public

  • 数据

  • data

  • mato.json(我的.JSON文件)

src

  • 组件

  • components

  • App.js

为什么我将文件放在 public 文件夹中?如果我使用 src 文件夹中的文件构建我的项目,我的文件将包含在生成的 main.js 中。命令纱线构建。

Why I put my file in public folder? If I build my project with file in src folder, my file will be include in the generated main.js by the command yarn build.

我想修改我的json文件,而不是总是重建我的应用程序。

I want modify my json file without always rebuild my app.

所以我不能使用如下代码:

So I can't use code like:

import Data from './mato.json'

...或者:

export default { 'mydata' : 'content of mato.json'} import data from 'mydata';

我试图获取我的.json文件,但文件方案不是 fetch()& chrome ..

I tried to fetch my .json file but "file scheme" isn't friend with fetch() & chrome..

(Chrome错误:index.js:6 Fetch API无法加载文件:/// D:/projects/data/mato.json.URL方案file不受支持。)

(Chrome error: "index.js:6 Fetch API cannot load file:///D:/projects/data/mato.json. URL scheme "file" is not supported.")

这是我的fetch代码:

This is my code for fetch:

fetch(`${process.env.PUBLIC_URL}/data/mato.json`) .then((r) => r.json()) .then((data) =>{ ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root')); })

它仅适用于Firefox。我也试过模式:'cors'并不是更好。

It's only works with Firefox. I also tried mode: 'cors' does not better.

当然我没有任何服务器 - 这是一个本地项目 - 所以如果有人知道如何在本地阅读我的JSON文件,我将非常感激。

And of course I don't have any server — it's a local project — so if someone knows how I can read my JSON file locally I will much appreciate.

推荐答案

我认为你的fetch参数是错误的。它应该是

I think your fetch argument is wrong. It should be

fetch('data/mato.json')

更多推荐

从公用文件夹ReactJS获取本地JSON文件

本文发布于:2023-10-31 19:04:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1546999.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件夹   文件   ReactJS   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!