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 data as a global
'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.
var data = require('./data.json');
Any advice on the best way, preferably the "React" way, would be much appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…