首页 > 解决方案 > 在 React.js 中读取 .md

问题描述

我想将文档GET的内容.md作为我的 React 组件中的字符串。出于某种原因,我XMLHttpRequest()正在记录我的index.html文件。为什么下面的代码会记录我的index.html文件而不是我的my-first-article.md文件?

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。

标签: javascriptreactjsxmlhttprequestmarkdown

解决方案


由于 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>
    );
  }
}

推荐阅读