首页 > 解决方案 > 从异步函数渲染反应本机孩子

问题描述

我正在尝试从一个 id 呈现一个反应原生组件,该 id 被提供给一个 http 请求,然后返回该组件可以使用的 json。由于 http 请求是异步的,因此传入 PostCard 渲染的数据是未定义的。我试图通过等待 getSinglePost 的返回来解决这个问题,但数据仍然未定义。如果不清楚,render 函数会调用 renderCard 函数,该函数应该等待 getSinglePost 函数的 json,然后返回填充的 PostCard 反应组件。有任何想法吗?

  async getSinglePost(id: string) {
    try {
      let url = preHTT + apiURL + port + 'post/id';
      url = url + '?postId=' + id;
      const response = await fetch(url, {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      });
      const responseJson: any = await response.json();
      // we should do better error handling gracefully
      if (responseJson['status'] === 'ERROR') {
        throw 'Could not retrieve data';
      }
      // console.log(responseJson['payload']);
      return responseJson['payload'];
    } catch (error) {
      console.error(error);
    }
  }

  async renderCard(id: string, type: string) {
    if (type === 'post') { ***here***
        const data = await this.getSinglePost(id);
        return <PostCard data={data} goToProfile={this.moveToProfileScreen}/>;
    } else {
      return <EventCard goToProfile={this.moveToProfileScreen}/>;
    }
}


        ***render/return stuff above***
        {this.state.markers.map((marker:any)  => (
          <Marker // marker on press function eventually
            key={marker['postid']}
            coordinate={marker['location']}
            image={this.emojiDict[marker['type']]}
            >
            <Callout>
              <View flex>
                {this.renderCard(marker['postId'], marker['contentType'])}
              </View>
            </Callout>
          </Marker>
        ***render/return stuff above***

标签: javascriptreactjsreact-nativeasynchronousasync-await

解决方案


render是同步的,不会等待异步例程完成。在这种情况下,组件应该在例程完成时重新渲染。

可以按如下方式完成:

  async componentDidMount() {
    try {
      const asyncData = await this.getAsyncData();
      this.setState({ asyncData });
    } catch (err) {
      // handle errors
    }
  }

  render() {
    if (this.state.asyncData) {
      // render child component that depends on async data
    } else {
      // initial render
    }
  }

推荐阅读