我有一个组件,该组件可以引入多个道具以使用URL,URL进而调用JSON数据的API。道具由一系列选择框收集,这些选择框将选择内容作为道具发送,然后组件将这些道具安装到axios.get调用中,如下所示:
axios.get(`/inventory_reporter_api/logs?stage=PRODUCTION&severity=${nextProps.selectedSeverity}&start=${nextProps.startDate}&end=${nextProps.endDate}`)
这是我的问题。如果缺少任何道具,则axios API调用将不起作用。例如,在上面的示例中,如果我没有nextProps.selectedSeverity,则api将返回错误。所以我的问题是上面的呼叫说“如果存在nextProps.selectedSeverity,然后在URL中添加“&severity = $ {nextProps.selectedSeverity}””的语法是什么?
答案 0 :(得分:1)
如果您有一系列道具,这很简单:
const names = [
"Severity",
"Priority",
"Importance",
"Urgency"
];
// ...using it...
const nextProps = {
selectedSeverity: 7,
selectedImportance: "high"
};
let url = names
.filter(name => nextProps["selected" + name] !== undefined)
.map(name => name.toLowerCase() + "=" + encodeURIComponent(nextProps["selected" + name]))
.join("&");
console.log(url);
nextProps["selected" + name] !== undefined
检查可以是适合您数据,"selected" + name in nextProps
等的任何检查。
有100万次旋转。例如,不是字符串串联,而是数组(或非数组对象都起作用)的数组:
const names = [
["severity", "selectedSeverity"],
["priority", "selectedPriority"],
["importance", "selectedImportance"],
["Urgency", "selectedUrgency"]
];
const nextProps = {
selectedSeverity: 7,
selectedImportance: "high"
};
// ...using it...
let url = names
.filter(([urlParam, propName]) => nextProps[propName] !== undefined)
.map(([urlParam, propName]) => urlParam.toLowerCase() + "=" + encodeURIComponent(nextProps[propName]))
.join("&");
console.log(url);
答案 1 :(得分:0)
尝试一下:
// for demo purposes
let nextProps = {
startDate: '1janv2019',
endDate: '10janv2019'
}
let url = '/inventory_reporter_api/logs?'
+ [
{ key: 'severity', var: nextProps.selectedSeverity },
{ key: 'start', var: nextProps.startDate },
{ key: 'end', var: nextProps.endDate }
]
.map(o => o.var ? `${o.key}=${o.var}` : '')
.join('&')
console.log(url);
答案 2 :(得分:0)
我将构建一个小的实用程序来构建params对象。
const buildParams = (input, paramKey, paramValue) => typeof paramValue !== 'undefined' ? { ...input, [paramKey]: paramValue } : input;
let params = { stage: 'PRODUCTION' };
params = buildParams(params, 'severity', nextProps.selectedSeverity);
params = buildParams(params, 'start', nextProps.startDate);
params = buildParams(params, 'end', nextProps.endDate);
axios.get('/inventory_reporter_api/logs', params)