创建反应应用公共文件夹json



找不到回答的确切问题。我想在我的/公共文件夹中有一个data.json文件,其中包含一个静态文件,该文件一旦构建了站点,我就可以快速修改,而无需重建网站。但是,我正在为如何将其带入反应而挣扎。我已经尝试按照读书文件的说明进行操作,但是还不清楚。

如果我尝试:

    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/.

包括它的正确方法是什么?我还尝试将其写入public/index.html中的data来尝试一种骇人听闻的方法似乎不喜欢它。我尝试的代码:

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);
  }
}

任何帮助将不胜感激!

借用"窗口"变量。

例如,在文件"/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>

如果要将文件放入公共文件夹中,则您的第一个解决方案将无效,因为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放在公共文件夹中,我有这样的对象:

{
  "Name": "My App"
}

我刚刚尝试过,它可以一直在页面中显示我的应用程序

您可以简单地这样做:

mydata.js

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

在您的代码中

import myData from './mydata.js'

您现在将数据放在一个称为myData

的变量中

最新更新