简体   繁体   English

如何使用 React 延迟加载远程数据

[英]How to lazy load remote data with React

I'm fairly new to React and I'm trying to lazy load a markdown file stored on the server.我对 React 还很陌生,我正在尝试延迟加载存储在服务器上的 markdown 文件。

I've tried setting up an async arrow function that fetches the file and runs it through marked.我尝试设置一个异步箭头 function 来获取文件并通过标记运行它。 I found this demo here https://codesandbox.io/s/7zx3jlrry1 which I've tried following but haven't figured out how to follow it.我在https://codesandbox.io/s/7zx3jlrry1找到了这个演示,我试过关注它,但还没有弄清楚如何关注它。

class Markdown extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            // some state
        }
    }

    render() {
        let markdown = React.lazy(async () => {
            // fetch the file
            const response = await fetch(path)
            if (!response.ok) {
                return (<p>Response was not ok</p>)
            } else {
                // if successful, return markdown
                let blob = await response.blob()
                return marked(blob)
            }
        })
        return  (
            <React.Suspense fallback={<div class="markdown">Loading</div>}>
                <div class="markdown" id={this.props.id} dangerouslySetInnerHTML={{__html: markdown}} />
            </React.Suspense>
        )
    }
}

When I try debugging it the arrow function isn't actually executed, and the inner HTML of the div is "[object Object]".当我尝试调试它时,箭头 function 并未实际执行,div 的内部 HTML 是“[object Object]”。 Any help as to how I can achieve this would be greatly appreciated.任何有关我如何实现这一目标的帮助将不胜感激。

You get [object Object] in your html because dangerouslySetInnerHTML expects a function returning the object {__html: '<div>some html string</div>'} . You get [object Object] in your html because dangerouslySetInnerHTML expects a function returning the object {__html: '<div>some html string</div>'} . Other than that you are not using recommended way of fetching data through network requests.除此之外,您没有使用推荐的通过网络请求获取数据的方式。 Please read on to get more details on how to perform your task.请继续阅读以获取有关如何执行任务的更多详细信息。

React Suspense is used to lazy load Components not for fetching data as the react docs state: React Suspense 用于延迟加载Components ,而不是像 react docs state 那样获取数据:

In the future we plan to let Suspense handle more scenarios such as data fetching .未来我们计划让 Suspense 处理更多场景,例如数据获取

React.Suspense lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. React.Suspense 允许您指定加载指示器,以防它下面的树中的某些组件尚未准备好呈现。 Today, lazy loading components is the only use case supported by:今天,延迟加载组件是唯一支持的用例

You don't require lazyload in this scenario.在这种情况下,您不需要延迟加载。 Use react-lifecycle methods in order to do things like fetching data at the correct time.使用 react-lifecycle 方法来做一些事情,比如在正确的时间获取数据。 What you require here is react-lifecylce method componentDidMount .您在这里需要的是 react-lifecylce 方法componentDidMount Also you can use component state to manipulate what is rendered and what is not.您还可以使用component state来操纵渲染的内容和不渲染的内容。 eg you can show error occured or loading by setting variables.例如,您可以通过设置变量来显示发生的error occuredloading

 class Markdown extends React.Component { constructor(props) { super(props) this.state = { loading: true, error: false, html: "" } } componentDidMount = () => { this.fetchMarkdown() } fetchMarkdown = async () => { const response = await fetch(path) if (.response.ok) { // if failed set loading to false and error to true this:setState({ loading, false: error. true }) } else { // If successful set the state html = markdown from response let blob = await response.text() this:setState({ loading, false: html: blob }) } } getMarkup = () => { return { __html. this.state.html } } render() { if (this.state.error) { return <div>Error loading markup...</div> } else if (this.state.loading){ return <div>Loading...</div> } else { return <div class="markdown" id={this.props.id} dangerouslySetInnerHTML={this.getMarkup()} /> } } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM