如何在反应js

时间:2017-03-28 11:09:28

标签: reactjs axios

我是初学者,我正在研究一个小应用程序,它经常提出api请求。因此,我面临的问题是,如果用户对这些字段进行了更改,那么会有一个页面,其中包含从db预填充的表单字段,我将新的字段值发布到db。当单击提交按钮时,将调用saveAndConttinue(),从那里根据条件调用addNewAddress()。但问题是我从addNewAddress获得的响应必须用于队列中的下一个api调用,但是它需要时间来获得响应,并且address_id的后调用具有空值。有没有什么方法可以在现在使用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));
}

1 个答案:

答案 0 :(得分:2)

在addNewAddress()返回的promise中添加addNewAddress()之后,你将不得不调用队列中的下一个请求:

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

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

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

  })
}

进行同步调用总是一个坏主意,我个人会反对它,只是在返回的承诺中进行下一次调用,如上所示。

相关问题