将 json 数据从本地文件加载到 React JS

我有一个 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;

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

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

任何关于最佳方式的建议,最好是“反应”方式,我们将非常感激!

300371 次浏览

You are opening an asynchronous connection, yet you have written your code as if it was synchronous. The reqListener callback 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.

Unless you are on a zero-latency quantum-entanglement connection, this is well after 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 data in the React component, so I can only suggest this theoretically: why not update your component in the callback?

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

I was trying to do the same thing and this is what worked for me (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

  1. Install json-loader:
npm i json-loader --save
  1. Create data folder in src:
mkdir data
  1. Put your file(s) there.

  2. Load your file:

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

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.

Take a look at this answer

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?

I will include a slightly modified version for using it in 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>
);
}
}

If you have couple of json files:

import data from 'sample.json';

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

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

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"
}
]

First , 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>