最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Render react native child from async function - Stack Overflow

programmeradmin3浏览0评论

I'm trying to render a react native ponent from an id, which is given to a http request and in turn returns json that the ponent can use. Since the http request is async, the data that is passed into the PostCard render is undefined. I tried to get around this by awaiting the return of getSinglePost, but data still remains undefined. In case it is unclear, the render function calls the renderCard function, which is supposed to wait for json from the getSinglePost function, which then returns a filled PostCard react ponent. Any ideas?

  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***

I'm trying to render a react native ponent from an id, which is given to a http request and in turn returns json that the ponent can use. Since the http request is async, the data that is passed into the PostCard render is undefined. I tried to get around this by awaiting the return of getSinglePost, but data still remains undefined. In case it is unclear, the render function calls the renderCard function, which is supposed to wait for json from the getSinglePost function, which then returns a filled PostCard react ponent. Any ideas?

  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***
Share Improve this question edited Jul 14, 2018 at 12:14 user10079769 asked Jul 14, 2018 at 7:32 Shekar Shekar 2501 gold badge6 silver badges14 bronze badges 1
  • 1 render must not be asynchronous, and you shouldn't do http requests from rendering anyway. – Bergi Commented Jul 14, 2018 at 7:38
Add a ment  | 

1 Answer 1

Reset to default 4

render is synchronous and won't wait for asynchronous routines to be pleted. In this case the ponent should be re-rendered on routine pletion.

It can be done as follows:

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

  render() {
    if (this.state.asyncData) {
      // render child ponent that depends on async data
    } else {
      // initial render
    }
  }
发布评论

评论列表(0)

  1. 暂无评论