javascript - 在 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。
解决方案
由于 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>
);
}
}
推荐阅读
- symfony - Symfony 5 为多用户类型生成身份验证
- java - 如何复制地图
- mysql - mysql - 从0到最大值计算列中数字的重复
- java - 将过滤后的 JTable 数据导出到文本文件
- sqflite - 使用 sqlflite not sharedpreference 进行拖放后如何保存可重新排序的列表视图?
- python - pandas Explode 产生意想不到的结果
- javascript - 如何在不使用路径元素坐标的情况下在 React 中的 SVG 路径元素上覆盖文本?
- python - 无法在 Pygame 无尽的跳线中使角色跳跃
- r - 无法使用相同的 Rmarkdown 输入输出到 pdf、word 和 HTML
- java - laravel 应用程序控制台中缺少根所需的参数