【发布时间】:2018-12-22 11:54:10
【问题描述】:
我正在尝试从一个 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***
【问题讨论】:
-
render不能是异步的,你也不应该从渲染中做 http 请求。
标签: javascript reactjs react-native asynchronous async-await