从本地文件加载到JSON数据作出反应JS [英] loading json data from local file into React JS

查看:168
本文介绍了从本地文件加载到JSON数据作出反应JS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个阵营组成部分,我想在我的JSON数据从文件中加载。控制台日志目前不工作,即使我创建变量数据作为一个全球性的

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;

在理想情况下,我会preFER做这样的事情,但它不工作 - JS,它尝试添加 到文件名末尾

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

这是最好的办法,preferably的响应的方式任何意见,将是非常美联社preciated!

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

推荐答案

您正在打开的<一个href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHtt$p$pquest/Synchronous_and_Asynchronous_Requests#Asynchronous_request"相对=nofollow>异步连接,但你写你的code,如果它是同步的。与你的code中的 reqListener 回调函数不会同步执行(即前 React.createClass ),但只有在你的整个片段已经运行,且响应已收到从远程位置。

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.

这是的以及的所有语句已经跑后。例如,要记录所接收的数据,则将:

This is well after all your statements have ran. 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?

我强烈建议考虑异步的,基于回调JavaScript编程,我觉得很有趣,耐人寻味自己。

I strongly recommend looking into asynchronous, callback based JavaScript programming, I find it fun and intriguing myself.

这篇关于从本地文件加载到JSON数据作出反应JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆