组织查询React Native的更好方法

问题描述 投票:-1回答:2

如果我想要限制和偏移是可选的怎么办?假设我有两个调用此方法的动作

  1. ProductRelatedDetail(catId,subCatId)
  2. ProductRelatedDetail(catId,subCatId,limit,offset)

我不想两次复制该功能。管理这种情况的更好,更有活力的方法是什么?

export function ProductRelatedDetail(catId, subCatId, limit, offset) {

  return function (dispatch) {

        return fetch(`${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}&limit=${limit}&offset=${offset}`, {
              method: 'POST',
              headers: myHeaders,
        })
              .then(res => res.json())
              .then(data => dispatch({
                    type: actionType.GET_RELATED_DETAIL,
                    payload: data
              })).catch(error => {
                    console.log('Got cat Feed', error);
              });
     }
};
reactjs react-native
2个回答
0
投票

我使用if语句如下:

export function ProductRelatedDetail(catId, subCatId, limit, offset) {

return function (dispatch) {
    if(!limit && !offset){
    return fetch(`${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}`, {
          method: 'POST',
          headers: myHeaders,
    })
          .then(res => res.json())
          .then(data => dispatch({
                type: actionType.GET_RELATED_DETAIL,
                payload: data
          })).catch(error => {
                console.log('Got cat Feed', error);
          });
    }else{
        return fetch(`${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}&limit=${limit}&offset=${offset}`, {
          method: 'POST',
          headers: myHeaders,
    })
          .then(res => res.json())
          .then(data => dispatch({
                type: actionType.GET_RELATED_DETAIL,
                payload: data
          })).catch(error => {
                console.log('Got cat Feed', error);
          });
    }
 }
};

希望能帮助到你。


0
投票

我想你有可能做到这样的事情:

return fetch(
"${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}" 
+ ((limit!=null) ? "&limit=${limit}" : "") 
+ ((offset!=null) ? "&offset=${offset}" : ""), ...
© www.soinside.com 2019 - 2024. All rights reserved.