从异步函数填充React prop对象

时间:2017-01-16 23:11:27

标签: javascript reactjs asynchronous

我的高级目标是能够将文本文件中的数据读取到我使用React创建的页面上。

我有一个实用程序脚本文件,我用它来按路径读取文件:

//reader.js
window.readFile = function(filePath, callback) {
  var request = new XMLHttpRequest();
  request.open("GET", filePath, true);
  request.send(null);
  request.onreadystatechange = function() {
    if (request.readyState === 4 && request.status === 200) {
      var type = request.getResponseHeader('Content-Type');
      if (type.indexOf("text") !== 1) {
        callback(null, request.responseText);
      }
    }
  }
}

我在我的一个React组件文件中调用了这个函数:

//component.js
var data = {};

populateData();

function populateData() {
  data.subject = "FILE TITLE";
  data.title = "FILE SUBJECT";
  window.readFile("../path/to/file", function(error, results){
    if (!error) {
      data.content = results;
    }
    else {
      console.log(error);
    }
  });
}

var Content = React.createClass({
  render: function() {
    return (
      <FileContent { ...data } />
    );
  }
});

我已经测试过该函数是否从这个上下文中正确运行了,但是由于readFile函数的异步性质,我的数据对象的内容字段似乎永远不会填充来自文件。是否存在同步返回我需要的方式,或者如何异步解决?

1 个答案:

答案 0 :(得分:2)

由于readFile函数的异步性质,您必须异步解决此问题。最简单的方法是向组件中添加一个调用该函数的方法,然后在完成后设置状态。完成后,您可以将数据传递给子组件。

例如:

var Content = React.createClass({
  getInitialState() {
    return {
      data: null
    }
  },

  componentDidMount() {
    this.populateData();
  },

  populateData() {
    const data = {};
    data.subject = "FILE TITLE";
    data.title = "FILE SUBJECT";
    window.readFile("../path/to/file", (error, results) => {
      if (!error) {
        data.content = results;
        this.setState({
          data
        });
      }
      else {
        console.log(error);
      }
    });
  },

  render: function() {
    const {data} = this.state;

    if (data === null) {
      // data has not been loaded yet
      // you can add a loading spinner here or some kind of loading component
      return null
    }

    return (
      <FileContent { ...data } />
    );
  }
});