我需要动态导入标记文件的一部分,并将结果添加到变量并在我的 React 应用程序中呈现结果:
import('../changelog.md').then(...)
我试图render()
用所有的逻辑方法来做,但我有问题。我需要在哪里导入它(在课堂上或外面)以及如何获得将其粘贴到变量的Promise值?
我需要动态导入标记文件的一部分,并将结果添加到变量并在我的 React 应用程序中呈现结果:
import('../changelog.md').then(...)
我试图render()
用所有的逻辑方法来做,但我有问题。我需要在哪里导入它(在课堂上或外面)以及如何获得将其粘贴到变量的Promise值?
这是一种方法:
class MyComponent extends React.Component {
state = {html: null}
componentDidMount() {
import('../changelog.md').then(mod => {
this.setState({html: mod.default})
})
}
render() {
return this.state.html ? <div dangerouslySetInnerHTML={{__html:this.state.html}} /> : <p>Loading...</p>
}
}
假设您有一个.md
加载程序并且它返回 HTML。
import()
返回一个 Promise。因此,您必须等待它解决才能渲染它。最简单的方法是这样做componentDidMount
(React建议您将所有 ajax 请求放在那里,这有点类似),然后将其复制到 state 中以在完成后强制重新渲染。
我会await
在async
方法中使用关键字。
async function render() {
var markup = await import('../changelog.md');
// ...
}
像这样在开始时导入您的 .md 文件。
import yourMDObject from '../changelog.md';
然后你可以fetch()
像这样使用
fetch(yourMDObject).then(obj =>obj.text()).then(..)