Redux传奇执行多个HTTP请求

时间:2019-01-10 07:49:07

标签: javascript reactjs redux redux-saga

我如何在Redux传奇中为该有效负载执行多个http请求:

 [
  {
    "product_ids": [
      "e331e78b-e954-4de3-9bb3-80827b0d0741"
    ],
    "body": {
      "command": "request",
      "data": {
        "api_key": "errtrt4i548",
        "api_username": "xxxx",
        "vendor_type": 1,
        "from": {
          "from_description": ""
        },
        "to": {
          "to_name": "Fat Rain Films",
          "to_lat": 36.77254990000006,
          "to_long": -1.2711643,
          "to_description": ""
        }
      }
    }
  },
  {
    "product_ids": [
      "9331e78b-e954-4de3-9bb3-80827b0d0741"
    ],
    "body": {
      "command": "request",
      "data": {
        "api_key": "errtrt4i548",
        "api_username": "xxxx",
        "vendor_type": 1,
        "from": {
          "from_description": ""
        },
        "to": {
          "to_name": "Fat Rain Films",
          "to_lat": 36.77254990000006,
          "to_long": -1.2711643,
          "to_description": ""
        }
      }
    }
  }
]

我的Saga代码是:

export function* getQoute({ qoute }) {
  yield put(updateNetworkStatus(true));

  const headers = {
    method: 'POST',
    // credentials: 'include',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(qoute),
  };
  const total = 0;
  try {
    const req = yield call(
      request,
      `${API_BASE}/shippings/shipping/initiate_delivery_sendy/`,
      headers,
    );
    console.log(req);
    // total += req.
  } catch (err) {
    console.log(err.message);
    //yield put(updateLoadingStatus(false));
  }
}

我遇到的挑战是找到一种方法,用有效载荷中的数据调用我的api。也就是说,在相同的传奇或动作中,调用api的次数是我的JSON有效负载中对​​象的2倍或数量。

1 个答案:

答案 0 :(得分:0)

对于您的情况,您可以遍历json数组并调度一个操作,以将每个对象作为有效负载来调用您的传奇。

说我有一个数组有效负载[2] = {obj1,obj2}。然后做

var i;
for (i = 0; i < payloads.length; i++) { 
yield put({type: YOUR_ACTION_TYPE_FOR_SAGA, payload: payloads[i]});
}