创建 React-App Public 文件夹 JSON

Create-React-App Public Folder JSON

找不到这个确切问题的答案。我想在我的 /public 文件夹中有一个 data.JSON 文件,其中包含一个静态文件,一旦网站建成,我就可以快速修改而无需重建网站。但是我正在努力研究如何让它做出反应。我尝试按照 README 的说明进行操作,但有点不清楚。

如果我尝试:

    class Home extends Component {
      render() {
        const data = require(`${process.env.PUBLIC_URL}/data.json`);

我在编译时收到消息:

./src/Home.js
    Module not found: You attempted to import /data.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.

包含它的正确方法是什么?我还尝试了一种 hacky 方式,试图将它写入 public/index.html 中的 window.DATA 但因为我相信它必须调用异步(否则 chrome 会给我一个错误)有时数据会在那里,有时不会,React 似乎不喜欢它。我试过的代码:

var request = new XMLHttpRequest();
request.open("GET", "%PUBLIC_URL%/data.json", true);
request.send(null);
request.onreadystatechange = function() {
  if ( request.readyState === 4 && request.status === 200 ) {
    window.DATA = JSON.parse(request.responseText);
  }
}

如有任何帮助,我们将不胜感激!

你可以简单地这样做:

mydata.js

export default {
  myStuff: [ "one","two","three"]
}

在你的代码中

import myData from './mydata.js'

您现在将数据保存在名为 myData

的变量中

如果您想将文件放在 public 文件夹中,您的第一个解决方案将不起作用,因为 React 不应允许访问源文件夹之外的内容。否则你可以想象一个错误的代码可以允许人们访问文件夹 c:\windows

您的第二个解决方案可能是可行的方法,但只需要在回调上做一些工作。如果您使用 create-react-app 启动您的项目,您可以将 index.js 设为

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

var xhttp = new XMLHttpRequest();
var data = {};
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
       // Typical action to be performed when the document is ready:
       data = JSON.parse(xhttp.responseText);
       ReactDOM.render(<App appData={JSON.stringify(data)}/>, document.getElementById('root'));
    }
};

xhttp.open("GET", `${process.env.PUBLIC_URL}/data.json`, true);
xhttp.send();

然后你的 App.js 作为

import React, { Component } from 'react';

class App extends Component {
  render() {
    return (
      <div>
          <h2>{JSON.parse(this.props.appData).Name}</h2>
      </div>
    );
  }
}

export default App;

我把data.json放在public文件夹里,我有这样的对象:

{
  "Name": "My App"
}

刚才试了一下,可以一直在页面显示我的应用

借用 "window" 变量。

例如,在文件“/public/config.js”中:

window.samleAppConfig = {
  entryUrl: "service.com/api"
}

然后在文件“/src/App.js”中:

constructor(props) {
  super(props);
  console.log('entryUrl', window.samleAppConfig. entryUrl);
}

并且在“/public/index.html”中:

<div id="root"></div>
<script type="text/javascript" src="config.js"></script>