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

How to lazy load remote data with React

我是 React 的新手,我正在尝试延迟加载存储在服务器上的降价文件。

我试过设置一个异步箭头函数来获取文件并通过标记运行它。 我在这里 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>
        )
    }
}

当我尝试调试它时,箭头函数实际上并没有执行,div 的内部 HTML 是“[object Object]”。 非常感谢任何有关我如何实现这一目标的帮助。

您在 html 中得到 [object Object],因为 dangerouslySetInnerHTML 需要一个返回对象 {__html: '<div>some html string</div>'} 的函数。除此之外,您没有使用推荐的方式通过网络请求获取数据。请继续阅读以获取有关如何执行任务的更多详细信息。

React Suspense 用于延迟加载Components而不是作为 React 文档状态获取数据:

In the future we plan to let Suspense handle more scenarios such as data fetching.

React.Suspense lets you specify the loading indicator in case some components in the tree below it are not yet ready to render. Today, lazy loading components is the only use case supported by :

在这种情况下您不需要延迟加载。使用反应生命周期方法来做一些事情,比如在正确的时间获取数据。这里需要的是react-lifecylce方法componentDidMount。您也可以使用 component state 来控制呈现的内容和不呈现的内容。例如,您可以通过设置变量来显示 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()} />
  }
 }
}