首页 > 解决方案 > 如何调用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});
        });
    }

标签: javascriptreactjspromise

解决方案


您可以将此单个组件拆分为两个 - 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>
    )
  }

}

推荐阅读