组织查询React Native的更好方法

时间:2018-09-01 07:36:41

标签: reactjs react-native

如果我希望 limit offset 是可选的怎么办?假设我有两个调用此方法的操作

  1. ProductRelatedDetail(catId,subCatId)
  2. ProductRelatedDetail(catId, subCatId,限制,偏移量)

我不想重复两次该功能。解决这种情况的更好,更动态的方法是什么?

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

2 个答案:

答案 0 :(得分: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);
          });
    }
 }
};

希望有帮助。

答案 1 :(得分:0)

我想您可能会做这样的事情:

return fetch(
"${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}" 
+ ((limit!=null) ? "&limit=${limit}" : "") 
+ ((offset!=null) ? "&offset=${offset}" : ""), ...