React Native 获取和渲染 json

所以我刚开始使用 React Native,我想获取一些 json 并在之后渲染一些组件。因此,我创建了一个返回 json的函数loadDocument()和一个如下所示的函数assembleDocument():


function assembleDocument() {

  return new Promise((resolve) => {

    loadDocument().then((doc) => {

      const first_row = doc.paragraphs[0].rows[0].blocks

      let container


      for (let block = 0; block < first_row.length; ++block) {

        container += <HanziBlock hanzi={first_row[block].hanzi} pinyin={first_row[block].pinyin} />

      }


      resolve(container)

    });

  });

}

一切似乎都运行良好,该函数返回一个包含我的“HanziBlock”组件的对象。现在我只需要渲染它:


export default function HomeScreen() {

  let content = await assembleDocument()

  return content;

}

但问题是:我不能在异步函数之外使用 await。但是,如果我不能等待我的内容到达,我该如何渲染它?


哆啦的时光机
浏览 155回答 1
1回答

慕容3067478

您应该单独加载文档并进行组装。也许这样的事情会为你工作。constructor() {&nbsp; this.state = { doc: null };}componentDidMount() {&nbsp; loadDocument().then((doc) => this.setState({ doc }));}render() {&nbsp; if (this.state.doc === null) {&nbsp; &nbsp; return 'Loading';&nbsp; }&nbsp; return assembleDocument(this.state.doc);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript