渲染来自异步函数的本机子级

时间:2018-07-14 07:32:40

标签: javascript reactjs react-native asynchronous async-await

我正在尝试从提供给http请求的id渲染React本机组件,然后返回该组件可以使用的json。由于http请求是异步的,因此传递到PostCard呈现器中的数据是不确定的。我试图通过等待getSinglePost的返回来解决此问题,但是数据仍然未定义。 如果不清楚,render函数将调用renderCard函数,该函数将等待getSinglePost函数中的json,然后返回已填充的PostCard react组件。 有什么想法吗?

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

1 个答案:

答案 0 :(得分:1)

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