首页 > 解决方案 > Redux saga 执行多个 HTTP 请求

问题描述

我如何在 redux saga 中为此有效负载执行多个 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": ""
        }
      }
    }
  }
]

我的传奇代码是:

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 2 次或与我的 json 有效负载中的对象数量一样多。

标签: javascriptreactjsreduxredux-saga

解决方案


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

假设我有一个数组 payloads[2] = {obj1, obj2}。然后做

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

推荐阅读