我想在我的React Component中以字符串形式GET文档的内容。由于某些原因,我的.md正在记录我的XMLHttpRequest()文件。为什么以下代码将记录我的index.html文件而不是我的index.html文件?

export default class Article extends React.Component {
  readTextFile = file => {
    var rawFile = new XMLHttpRequest();
    rawFile.open('GET', file, false);
    rawFile.onreadystatechange = function() {
      if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
          var allText = rawFile.responseText;
          console.log(allText);
        }
      }
    };
    rawFile.send(null);
  };

  render() {
    return (
      <article>
        {this.readTextFile('./data/posts/my-first-article.md')}
      </article>
    );
  }
}


如果有帮助,目录中的相关文件的结构如下:

src/
  article.js
  data/
    posts/
      my-first-article.md


提前TY。

最佳答案

由于Web访问的异步性质,应使用异步方法。在这种情况下,可以在构造函数中初始化组件的状态,并在收到结果后将其设置为新值。状态更改时,将自动完成组件的新渲染。

export default class Article extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      content: null
    }
  }

  componentDidMount() {
    this.readTextFile('./data/posts/my-first-article.md')
  }

  readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open('GET', file);
    rawFile.onreadystatechange =  () => {
      if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
          var allText = rawFile.responseText;
          this.setState({ content: allText });
        }
      }
    };
    rawFile.send(null);
  };

  render() {
    return (
      <article>
        { this.state.content }
      </article>
    );
  }
}

10-06 04:26
查看更多