admin管理员组文章数量:1332896
I need to import markup file dynamically slice part of file and add result to variable and render result in my React app:
import('../changelog.md').then(...)
I trying to do it in render()
method with all logic but I have problems. Where I need to import it (in class or outside) and how to get value of promise to paste it to variable?
I need to import markup file dynamically slice part of file and add result to variable and render result in my React app:
import('../changelog.md').then(...)
I trying to do it in render()
method with all logic but I have problems. Where I need to import it (in class or outside) and how to get value of promise to paste it to variable?
-
import()
isn't any different than any other promise in this regard. CallsetState
inthen
. Wherever possible, use synchronous import. It's unclear from the question why would it be dynamic, since import module is known. – Estus Flask Commented Sep 14, 2018 at 17:11 - assuming this is a real changelog, it isn't going to change while the app runs, because the app won't be silently live-updating itself. Parse the .md file to something JS can work with during your build step and bundle that in. – Mike 'Pomax' Kamermans Commented Sep 14, 2018 at 17:42
3 Answers
Reset to default 5Here's one way:
class MyComponent extends React.Component {
state = {html: null}
ponentDidMount() {
import('../changelog.md').then(mod => {
this.setState({html: mod.default})
})
}
render() {
return this.state.html ? <div dangerouslySetInnerHTML={{__html:this.state.html}} /> : <p>Loading...</p>
}
}
Assuming you have a .md
loader and it returns HTML.
import()
returns a Promise. So you'll have to wait for it to resolve before you can render it. Easiest way to do that is to do it in ponentDidMount
(React remends you put all ajax request there and this is kind of similar) and then copy it into state to force a re-render when it's done.
I'd use await
keyword within an async
method.
async function render() {
var markup = await import('../changelog.md');
// ...
}
import your .md file at start like this.
import yourMDObject from '../changelog.md';
and then you can use fetch()
like this
fetch(yourMDObject).then(obj =>obj.text()).then(..)
本文标签: javascriptDynamic import() file in JSStack Overflow
版权声明:本文标题:javascript - Dynamic import() file in JS - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742314185a2451481.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论