javascript - 如何调用rest api并将结果提供给后续的promise调用
问题描述
我有以下代码调用 rest api,然后使用结果数据并将值提供给后续的 api 调用。不知道如何使这项工作..!您可以在第二种方法中看到我的评论,这会显示数据,但因为这是一个承诺,我不确定如何将其传回?
有任何想法吗?谢谢
代码片段
componentDidMount() {
myMethod();
}
getBookings(id) {
getCustomerBookings(id).then(res => {
console.log(res); // displays the data correctly
return res;
});
}
myMethod() {
var self = this;
var myArray = [];
getCustomers().then(result => {
for(var index = 0; index < result.length; index++) {
myArray.push(<div className="col">
{result[index].customerId} // displays customer id as expected
{this.getBookings(result[index].customerId)} // attempt
</div>
self.setState({customers: myArray});
});
}
解决方案
您可以将此单个组件拆分为两个 - CustomerContainer 和 Customer,并将第二个 API 调用绑定到 Customer 组件的安装。
import React, { Component } from 'react';
class CustomerContainer extends Component {
constructor() {
super();
this.state = {
customers = []
}
}
async getCustomers() {
// fetch customers
}
async componentDidMount() {
customers = await this.getCustomers();
this.setState({ customers })
}
render() {
const { customers } = this.state
return (
{customers.length > 0 && customers.map(customer => {
return <Customer customerId= {customer.id} />
})}
)
}
}
class Customer extends Component {
constructor() {
super();
this.state = {
bookings = [];
}
}
async getBookings(id) {
// fetch booking
}
async componentDidMount() {
bookings = await this.getBookings(this.props.customerId);
this.setState({ bookings })
}
render() {
const { bookings } = this.state;
return (
<div className="col">
{this.props.customerId} // displays customer id as expected
</div>
)
}
}
推荐阅读
- ios - 错误:未知的应用程序扩展“。” - 预期的“.app”或“.ipa”
- react-native - React Native WebView - 仅在用户交互的情况下在外部浏览器中打开链接
- python - Python将输入文件中的行/单词拆分为变量
- excel - VBA Date + TimeValue 不返回时间
- c++ - cpp 函数,根据模板类型返回值
- spring-boot - 如果我想保存以下类型的 JSON 对象,如何在 Java 中构造 DTO。使用杰克逊
- reactjs - TextField 只接受一个字母并失去焦点
- android - 加载时在webview中显示白页(PDF url)url android
- python - 覆盖类变量和并发 Flask 请求
- firebase - 如何从 Firebase REST API 获取排序数据