从 public 文件夹中获取本地 JSON 文件 ReactJS

Fetch local JSON file from public folder ReactJS

两天前我就遇到了问题;我想从使用 react-app 创建的 React 应用程序的 public 文件夹中读取本地 JSON。

这是我的项目结构:

为什么我将文件放在 public 文件夹中?如果我使用 src 文件夹中的文件构建我的项目,我的文件将包含在命令 yarn build.

生成的 main.js

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

所以我不能使用像这样的代码:

import Data from './mato.json'

……或者:

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

我试图获取我的 .json 文件,但 "file scheme" 不是 fetch() & chrome..

的朋友

(Chrome 错误:“index.js:6 Fetch API 无法加载文件:///D:/projects/data/mato.json。[=不支持 90=] 方案 "file"。”)

这是我的获取代码:

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。我也试过mode: 'cors'也没有更好。

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

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

fetch('data/mato.json')

只要数据文件放在 public 文件夹中,它就应该在 Chrome 中工作,就像在我的项目中一样。 所以,fetch('data/mato.json') 就够了。

您还需要传入一些 headers 表示 Content-TypeAccept 作为 application/json 告诉您的客户您正在尝试访问并接受一些 JSON 来自服务器的资源。

  const getData=()=>{
    fetch('data/mato.json'
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        console.log(response)
        return response.json();
      })
      .then(function(myJson) {
        console.log(myJson);
      });
  }
  useEffect(()=>{
    getData()
  },[])

为什么要使用 fetch?我觉得速度有点慢。。。 我认为这个解决方案会更好...... 您可以将此行添加到您的 index.html:

<script type="text/javascript" src="settings.js"></script>

然后在 settings.js 你可以这样做:

 window.globalTS= {
  "site_url": "hi.com",
  "home_url": "hello.com"
};

现在在您的组件中,您可以像这样访问变量:

console.log(window.globalTS.site_url);

分享并评论你的想法,谢谢!

给出 public 文件夹中的 JSON 文件名并存储数据链接

componentDidMount() {
    fetch("./url.json")
      .then((res) => res.json())
      .then((data) => {
        this.setState({ links: data });
        console.log(this.state);
      });
  }