0

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

我决定不使用地图功能,而是通过删除地图进行一次调用。

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);
  });
}

有人可以建议我在这里做的最好的事情是什么。

4

1 回答 1

1

好吧,您的代码仍然有点复杂,并且您在循环中有一个循环,这在这里似乎有点不必要。

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

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);
}
于 2019-03-16T19:19:38.700 回答