javascript - 从异步函数渲染反应本机孩子
问题描述
我正在尝试从一个 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
是同步的,不会等待异步例程完成。在这种情况下,组件应该在例程完成时重新渲染。
可以按如下方式完成:
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
}
}
推荐阅读
- latex - ***(作业中止,未找到合法 \end)LaTex 中的错误
- python - 使用 Python 登录 Gmail 并检测登录失败
- sql-server - ELO ECM 套件 20
- laravel - 如何用背包forlaravel上的html图标替换动作
- google-analytics - 我可以在没有分析的情况下使用 Google AdSense 吗?
- python - 在带有循环的函数中返回后输入什么?
- arrays - 对指针和双指针的特定用户案例的误解
- animation - 如何反转动画运动?
- python - 如何在 Python 中将列表分成大小交替的块?
- amazon-web-services - CloudWatch 警报将 terraform 用于负载均衡器