【发布时间】:2021-08-05 11:03:39
【问题描述】:
使用下面的代码,我可以将本地文本文件的内容呈现到网页,但是当我使用 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;
【问题讨论】:
-
您可以使用 iframe。 这里的 src 属性值就是你的 URL
标签: javascript reactjs