如何在react js中发出同步的API调用请求

Cha*_*ram 3 reactjs axios

我是反应 js 的初学者,我正在开发一个经常发出 api 请求的小应用程序。所以我面临的问题是有一个页面包含从数据库预填充的表单字段,如果用户对这些字段进行更改,我会将新提交的值发布到数据库。单击提交按钮时,将调用 saveAndConttinue(),然后根据条件调用 addNewAddress()。但问题是我从 addNewAddress 获得的响应必须用于队列中的下一个 api 调用,但是获取响应需要时间,并且 address_id 的 post 调用具有空值。现在有什么方法可以在不使用flux/redux的情况下进行同步调用?

saveAndContinue(e) {
e.preventDefault();

if(this.props.params.delivery === 'home_delivery' && this.state.counter) {
  this.addNewAddress();
}

console.log('add id is '+this.state.address_id);
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
let fd = new FormData();
fd.append('token', this.props.params.token);
fd.append('dish_id', this.props.params.dish_id);
fd.append('address_type', this.props.params.delivery);
fd.append('address_id', this.state.address_id);
fd.append('ordered_units', this.props.params.quantity);
fd.append('total_cost', this.props.params.total_cost);
fd.append('total_service_charge', this.props.params.service_charge);
fd.append('net_amount', this.props.params.net_cost);
fd.append('hub_id', this.props.params.hub_id);
fd.append('delivery_charge', this.props.params.delivery_charge);
fd.append('payment_type', this.state.payment_type);
fd.append('device_type', 'web');

axios.post(myConfig.apiUrl + '/api/foody/orders/purchase' , fd, config)
        .then(function(response){
    if(response.data.success) {
      console.log(response);
      browserHistory.push('/order_confirmed/');
    } else {
      console.log(response);
      //alert(response.data.message)
    }
        });
}

addNewAddress() {
 const config = { headers: { 'Content-Type': 'multipart/form-data' } };
 let fd = new FormData();

  if(this.props.params.user_type === 'new') {
    fd.append('type', 'PRIMARY');
  }

  fd.append('token', this.props.params.token);
  fd.append('block', this.state.block);
  fd.append('door_num', this.state.door_num);
  fd.append('address', this.props.params.address);
  fd.append('locality', this.props.params.locality);
  fd.append('landmark', this.props.params.landmark);
  fd.append('hub_id', this.props.params.hub_id);
  axios.post(myConfig.apiUrl + '/api/user/add-address' , fd, config)
    .then(function(response){
      this.setState({address_id: response.data.data['id']});
      console.log(this.state.address_id);
    }.bind(this));
}
Run Code Online (Sandbox Code Playgroud)

小智 5

您将不得不在 addNewAddress() 返回的承诺中的 addNewAddress() 之后调用队列中的下一个请求:

addNewAddress() {
  axios.post()...
  .then(function (response) {

    // Set state
    this.setState({address_id: response.data.data['id']});

    // [Call next API request here]
    // ...

  })
}
Run Code Online (Sandbox Code Playgroud)

进行同步调用总是一个坏主意,我个人建议不要这样做,只需在返回的承诺中进行下一次调用,如上所示。