Javascript 将本地文件中的 json 数据加载到 React JS 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31758081/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:09:12  来源:igfitidea点击:

loading json data from local file into React JS

javascriptajaxjsonxmlhttprequestreactjs

提问by Desmond

I have a React component and I want to load in my JSON data from a file. The console log currently doesn't work, even though I'm creating the variable dataas a global

我有一个 React 组件,我想从文件中加载我的 JSON 数据。控制台日志当前不起作用,即使我将变量数据创建为全局

'use strict';

var React = require('react/addons');

// load in JSON data from file
var data;

var oReq = new XMLHttpRequest();
oReq.onload = reqListener;
oReq.open("get", "data.json", true);
oReq.send();

function reqListener(e) {
    data = JSON.parse(this.responseText);
}
console.log(data);

var List = React.createClass({
  getInitialState: function() {
    return {data: this.props.data};    
  },
  render: function() {
    var listItems = this.state.data.map(function(item) {
        var eachItem = item.works.work;        

        var photo = eachItem.map(function(url) {
            return (
                <td>{url.urls}</td> 
            )
        });
    });
    return <ul>{listItems}</ul>
  }
});

var redBubble = React.createClass({
    render: function() {
      return (
        <div>
          <List data={data}/>          
        </div>
      );
    }
  });

module.exports = redBubble;

Ideally, I would prefer to do it something like this, but it's not working - it tries to add ".js"onto the end of the filename.

理想情况下,我更愿意这样做,但它不起作用 - 它试图将“.js”添加到文件名的末尾。

var data = require('./data.json');

Any advice on the best way, preferably the "React" way, would be much appreciated!

任何关于最佳方式的建议,最好是“反应”方式,将不胜感激!

采纳答案by John Weisz

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListenercallback function will not execute synchronously with your code (that is, before React.createClass), but only after your entire snippet has run, and the response has been received from your remote location.

您正在打开一个异步连接,但您编写的代码就好像它是同步的一样。该reqListener回调函数将不会与你的代码同步执行(即前React.createClass),但你的整个段已运行后,才和响应已经从远程位置接收。

Unless you are on a zero-latency quantum-entanglement connection, this is wellafter all your statements have run. For example, to log the received data, you would:

除非您处于零延迟量子纠缠连接上,否则在您的所有语句都运行之后这很好。例如,要记录接收到的数据,您将:

function reqListener(e) {
    data = JSON.parse(this.responseText);
    console.log(data);
}

I'm not seeing the use of datain the React component, so I can only suggest this theoretically: why not updateyour component in the callback?

我没有看到dataReact 组件中的使用,所以我只能从理论上建议:为什么不在回调中更新你的组件?

回答by rockfakie

I was trying to do the same thing and this is what worked for me (ES6/ES2015):

我试图做同样的事情,这对我有用(ES6/ES2015):

import myData from './data.json';

I got the solution from this answer on a react-native thread asking the same thing: https://stackoverflow.com/a/37781882/176002

我从本机线程上的这个答案中得到了解决方案:https: //stackoverflow.com/a/37781882/176002

回答by César D. Velandia

The simplest and most effective way to make a file available to your component is this:

使文件可用于您的组件的最简单和最有效的方法是:

var data = require('json!./data.json');

Note the json!before the path

注意json!路径之前

回答by ChaosPredictor

  1. install json-loader:

    npm i json-loader --save

  2. create datafolder in src:

    mkdir data

  3. put your file(s) there

  4. load your file

    var data = require('json!../data/yourfile.json');

  1. 安装json-loader

    npm i json-loader --save

  2. datasrc以下位置创建文件夹:

    mkdir data

  3. 把你的文件放在那里

  4. 加载你的文件

    var data = require('json!../data/yourfile.json');

回答by jsbisht

If you have couple of json files:

如果您有几个 json 文件:

import data from 'sample.json';

If you were to dynamically load one of the many json file, you might have to use a fetchinstead:

如果您要动态加载众多 json 文件之一,则可能必须使用 afetch来代替:

fetch(`${fileName}.json`)
  .then(response => response.json())
  .then(data => console.log(data))

回答by Khadim Rana

My JSON file name: terrifcalculatordata.json

[
    {
      "id": 1,
      "name": "Vigo",
      "picture": "./static/images/vigo.png",
      "charges": "PKR 100 per excess km"
    },
    {
      "id": 2,
      "name": "Mercedes",
      "picture": "./static/images/Marcedes.jpg",
      "charges": "PKR 200 per excess km"
    },
    {
        "id": 3,
        "name": "Lexus",
        "picture": "./static/images/Lexus.jpg",
        "charges": "PKR 150 per excess km"
      }
]

1st Import on top:

import calculatorData from "../static/data/terrifcalculatordata.json";

then after return:

                  <div>
                      {
                        calculatorData.map((calculatedata, index) => {
                          return(
                          <div key={index}> 
                            <img
                            src={calculatedata.picture}
                            class="d-block"
                            height="170"
                          />
                          <p>
                            {calculatedata.charges}
                          </p>
                     </div>

回答by Rishab Doshi

You could add your JSON file as an external using webpack config. Then you can load up that json in any of your react modules.

您可以使用 webpack 配置将 JSON 文件添加为外部文件。然后您可以在任何反应模块中加载该 json。

Take a look at this answer

看看这个答案

回答by bizi

If you want to load the file, as part of your app functionality, then the best approach would be to include and reference to that file.

如果您想加载文件,作为应用程序功能的一部分,那么最好的方法是包含并引用该文件。

Another approach is to ask for the file, and load it during runtime. This can be done with the FileAPI. There is also another StackOverflow answer about using it: How to open a local disk file with Javascript?

另一种方法是请求文件,并在运行时加载它。这可以通过FileAPI来完成。还有另一个关于使用它的 StackOverflow 答案: How to open a local disk file with Javascript?

I will include a slightly modified version for using it in React:

我将包含一个稍微修改过的版本,以便在 React 中使用它:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null
    };
    this.handleFileSelect = this.handleFileSelect.bind(this);
  }

  displayData(content) {
    this.setState({data: content});
  }

  handleFileSelect(evt) {
    let files = evt.target.files;
    if (!files.length) {
      alert('No file select');
      return;
    }
    let file = files[0];
    let that = this;
    let reader = new FileReader();
    reader.onload = function(e) {
      that.displayData(e.target.result);
    };
    reader.readAsText(file);
  }

  render() {
    const data = this.state.data;
    return (
      <div>
        <input type="file" onChange={this.handleFileSelect}/>
        { data && <p> {data} </p> }
      </div>
    );
  }
}