【问题标题】:How to render a text file from a URL using reactjs如何使用 reactjs 从 URL 呈现文本文件
【发布时间】: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


【解决方案1】:

在将内容渲染到 DOM 之前,验证是否从 url 读取文件。

请尝试以下代码,

fetch("https://URL/file").then((r)=>{r.text().then(d=>console.log(d))})

尝试这个问题Get text from a txt file in the url中提到的步骤

【讨论】:

  • 无法在控制台中看到任何内容。
  • 请检查 url,数据是否可用,或者是否需要一些权限(如登录凭据或密码)才能从 url 读取数据
  • 数据在文本文件中可用,不需要任何权限即可访问。您可以检查上面给出的沙箱代码中给出的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-24
  • 1970-01-01
  • 2019-10-31
  • 2021-10-07
  • 1970-01-01
  • 2021-05-11
  • 2021-11-15
相关资源
最近更新 更多