如果我想要限制和偏移是可选的怎么办?假设我有两个调用此方法的动作
我不想两次复制该功能。管理这种情况的更好,更有活力的方法是什么?
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);
});
}
};
我使用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);
});
}
}
};
希望能帮助到你。
我想你有可能做到这样的事情:
return fetch(
"${constants.API}?tag=product_list&category_id=${catId}&sub_category_id=${subCatId}"
+ ((limit!=null) ? "&limit=${limit}" : "")
+ ((offset!=null) ? "&offset=${offset}" : ""), ...