react中,使用发送请求的方式把static文件夹中的前端可访问的静态文件读取成字符串:
1、new request,需要用到getRequestHeaders组件
2、fetch获取response
3、return response.text() 获取文件内容(关于response对象的属性和方法见:https://developer.mozilla.org/zh-CN/docs/Web/API/Response 。在这里,return response.tx()返回的是一个promise对象,这里我也没搞懂,promise对象到底是什么,以及到底是同步的还是异步的,后续还需要再看一下。https://www.cnblogs.com/whybxy/p/7645578.html )
import React, { Component } from 'react'; import { getRequestHeaders } from '../setupAjaxHeaders'; import HyperDown from 'hyperdown'; import './ReadMePage.css'; class ReadMePage extends Component { constructor(props){ super(props);
this.state={ readmeHtml:undefined, }; } render(){ const getArtifactRequest = new Request(require('../static/readme.md'), { method: 'GET', headers: new Headers(getRequestHeaders(document.cookie)) }); fetch(getArtifactRequest).then((response) => { return response.text() }).then((text) => { const parser=new HyperDown; this.state.readmeHtml=parser.makeHtml(text); this.setState({ readmeHtml:parser.makeHtml(text), }); return <div id="readMeBody" dangerouslySetInnerHTML={{__html:this.state.readmeHtml}}></div>; }); return <div id="readMeBody" dangerouslySetInnerHTML={{__html:this.state.readmeHtml}}></div>; } } export default ReadMePage;