如何更好地通过 AXIOS Api 调用在 React JS 中发送可选参数

How to better way to send optional params in react JS with AXIOS Api call

我正在尝试使用 AXIOS 在 React JS 中制作 API。我需要发送不同类型的参数取决于参数的可用性。目前,我正在调用下面的代码片段,它正在按预期工作。当我有更多的可选值时,代码会变得更长。我如何简化或优化下面的 api 调用

const axiosHandler = () => {
   
        let request;
        if (productID && type) {
            request = common.fetchDetails(
                { productID: productID, type: type },
                {
                    assignedTo: popUpID.current.toString(),
                    selectedItems: checkedItems,
                },
            );
        } else if (productID) {
            request = common.fetchDetails(
                { productID: productID },
                {
                    assignedTo: popUpID.current.toString(),
                    selectedItems: checkedItems,
                },
            );
        } else if (type) {
            request = common.fetchDetails(
                { type: type },
                {
                    assignedTo: popUpID.current.toString(),
                    selectedItems: checkedItems,
                },
            );
        } else {
            request = common.fetchDetailsWithoutParams({
                assignedTo: popUpID.current.toString(),
                selectedItems: checkedItems,
            });
        }
        request
            .then((res) => {
                console.log('res', res);
            })
            .catch((err) => {
                console.log('err', err);
            });
    };

您可以使用扩展运算符来创建对象 例如,为您的参数创建对象:

  { ...(productID && false),  ...(type && false) }

在这种方法中,例如如果 productID 为真 return {productID:productID} 如果类型为真 return {type:type} 最后如果两者都为真 return {productID:productID , type:type} 如果有任何参数未定义或为 null : 在 false 之前传播 object 中没有任何 return : 例如 return {...false,...false} = {}

const axiosHandler = () => {

    let request;
    /**
    var productID='';var type=''; //modify this to test as per your neds
    var param ={
    ...(productID && {productID: productID}),
    ...(type && {type: type})
    }
    console.log(param)
    */

    if (productID && type) {

      //Use conditional spread operator
      const arg1 = {
        ...(productID && {
          productID: productID
        }),
        ...(type && {
          type: type
        })
      }
      const arg2 = {
        assignedTo: popUpID.current.toString(),
        selectedItems: checkedItems,
      }

      if (arg1) { //if both productID and type are empty arg1 will be undefined.
        request = common.fetchDetails(arg1, arg2);
      } else {
        request = common.fetchDetails(arg2);
      }

      request
        .then((res) => {
          console.log('res', res);
        })
        .catch((err) => {
          console.log('err', err);
        });
    };

说明: 您可以使用条件扩展运算符来实现此目的。

在这里查看更多:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax