【问题标题】:What is the best way to format this in React/JS? [closed]在 React/JS 中格式化它的最佳方法是什么? [关闭]
【发布时间】:2019-01-07 19:05:40
【问题描述】:

我有一个组件正在拉入多个道具以使用一个 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 然后将“&severity=${nextProps.selectedSeverity}”添加到 URL,但如果没有,请不要添加它。感谢任何帮助提前。

【问题讨论】:

  • 只需检查这些值是否存在,然后构建 url 字符串?

标签: javascript reactjs syntax


【解决方案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 等。

有一百万次旋转。例如,不是字符串连接,而是一个数组数组(或非数组对象,两者都可以):

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

【讨论】:

  • 非常感谢,T.J.!
  • @CHays412 - 不用担心!如果此答案或任何其他答案回答您的问题,Stack Overflow 的工作方式,您将通过单击旁边的复选标记“接受”该答案; details here。但前提是您的问题得到了真正的回答。
【解决方案2】:

试试这个:

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

【讨论】:

  • 谢谢尼诺,我会试试这个!
  • 问题是,如果nextProps为空,会在URL中输入“&”,导致报错。
【解决方案3】:

我会构建一个小实用程序来构建 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)

【讨论】:

    猜你喜欢
    • 2020-03-25
    • 2016-11-23
    • 2011-06-17
    • 1970-01-01
    • 2022-10-18
    • 2018-05-24
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多