首页 > 解决方案 > 如何使用 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;

标签: javascriptreactjs

解决方案


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

请尝试以下代码,

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

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


推荐阅读