通过删除 map 函数进行一次性 API 调用

Making a one time API call by removing the map function

我是 ReactJs 的新手,我很难理解下面的变化。提交表单时,以下代码会根据存在的项目数调用 API。

我决定不使用 map 函数,而是通过删除 map 进行一次调用。

submitForm() {
  // Remove map from below and make it as a single call instead multiple calls to API
  const bucketsInfo = formState.formData.step1.variants.map((item, i) => {
    const formBody = {
      buckets: [],
      control: formState.formData.step2.controlOptions
    };
    formState.formData.step2.variants.forEach((items, j) => {
      formBody.buckets.push({
        crossDomainSiteId: formState.formData.step2.variants[j].siteID.value,
      });
    });
    return axios.post("/guinness_api/experiments/experiment", formBody);
  });
}

谁能告诉我这里最好的事情是什么。

好吧,你的代码还是有点复杂,而且你有一个循环中的循环,在这里看起来有点不必要。

如果我正确理解您在这里需要什么,重构的示例将是:

submitForm() {
    const { step2 } = formState.formData;
    const step2Variants = step2.variants;

    // Map already returns each variant, no need to foreach it with index
    const buckets = step2Variants.map(variant => ({
      crossDomainSiteId: variant.siteID.value
    }));

    /** Creates formbody object from buckets populated with map, 
     *    and takes control options from step 2 
     */
    const formBody = {
      buckets,
      control: step2.controlOptions
    };

    return axios.post('/guinness_api/experiments/experiment', formBody);
}