javascript - 如何使用 reactjs 从 URL 呈现文本文件
问题描述
使用下面的代码,我可以将本地文本文件的内容呈现到网页,但是当我使用 URL 获取文本文件以将其呈现在网页上时,我得到" "
了,因为状态已定义null
。要渲染本地文本文件,我必须使用import text from './filepath.txt
. 如何从 URL 链接呈现文本内容?
import React, { Component } from "react";
import "./App.css";
import text from "./myText.txt";
class App extends Component {
state = { loading: true,
docText: null,
};
componentDidMount() {
fetch( text, { mode: "no-cors" }
// {
// method: "GET",
// headers: {
// "Content-Type": "application/text",
// },
// }
).then((response) => { return response.text();})
.then((data) => {
this.setState({ docText: data, loading: false });
console.log({ docText: data });
})
.catch((error) => { console.log(error);
});
}
render() {
return (
<div className="App">
<h1>Fetched Data</h1>
<div>
{this.state.loading || !this.state.docText ? (
<div>Loading...</div>
) : (
<div>
<div>{this.state.docText}</div>
</div>
)}
</div>
</div>
);
}
}
export default App;
解决方案
在将内容渲染到 DOM 之前,请验证是否从 url 读取文件。
请尝试以下代码,
fetch("https://URL/file").then((r)=>{r.text().then(d=>console.log(d))})
尝试此问题中提到的步骤Get text from a txt file in the url
推荐阅读
- python - 在Django中显示从应用程序到网站主页的单个记录
- python - 如何使用 python-docx 或任何其他类似的包从 Word 文档中保存字体样式(粗体和斜体)
- html - 如何在wordpress中循环出html代码?
- javascript - 在通过开发工具手动提交之前,Vuex 不会提交更改
- python - 使用 python 将 powerpoint 演示文稿分成一组幻灯片
- node.js - 如何使用 .sh 文件配置 heroku psql 数据库?
- python - 根据 csv 文件移动文件
- javascript - Three.js 对象不显示,只显示黑屏
- reactjs - 如何解决“列表中的每个孩子都应该有一个唯一的“关键”道具。
- ios - Live Admob 广告突然停止在我的应用中显示