如果我希望 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);
});
}
};
答案 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}" : ""), ...