简体   繁体   English

模板文字连接中的条件语句?

[英]Conditional statement within template literal concatenation?

I am making an API call like this:我正在进行这样的 API 调用:

posts: (ppp, page) =>
    requests.get(`/wp-json/wp/v2/posts?per_page=${ppp}&page=${page}`)

I am not always going to be passing in posts per page or page though, so I would like to only concatenate those variables if they exist.不过,我并不总是每页或每页传递帖子,所以我只想连接这些变量(如果它们存在)。 I tried below but I can't seem to get the formatting down:我在下面尝试过,但似乎无法将格式设置为:

requests.get(`/wp-json/wp/v2/posts?`${ppp ? `'per_page='${ppp} : `''` `${page} ? `'&page=' ${page}` :''`)

Besides that your second solution contains syntax errors, it also isn't the most readable way to do that...除了您的第二个解决方案包含语法错误之外,它也不是最易读的方法......

But why are you trying to reinvent the wheel?但是你为什么要重新发明轮子呢?

You can use the URL API which is available both on the client-side and in Node.js :您可以使用在客户端Node.js 中都可用的URL API:

posts: (ppp, page) => {
  const url = new URL('/wp-json/wp/v2/posts')
  if(ppp) url.searchParams.append('per_page', ppp)
  if(page) url.searchParams.append('page', page)
  return requests.get(url.href)
}  

However, if you can't use the above solution for some reason, you can still implement a similar algorithm that works like the above solution.但是,如果由于某种原因无法使用上述解决方案,您仍然可以实现与上述解决方案类似的算法。 For example, you can use an array:例如,您可以使用数组:

posts: (ppp, page) => {
  const urlParams = []
  if(ppp) urlParams.push(`per_page=${ppp}`)
  if(page) urlParams.push(`page=${page}`)
  return requests.get(`/wp-json/wp/v2/posts?${ urlParams.join('&') }`)
}  

Or an even more flexible solution:或者更灵活的解决方案:

posts: (ppp, page) => {
  const urlParams = {
    per_page: ppp, //per_page=ppp
    page,          //page=page
                   //Add more here if you want
  }
  return requests.get(`/wp-json/wp/v2/posts?${ 
    Object
      .entries(urlParams)
      .filter(([k, v]) => v) //If value is truthy
      .map(e => e.join('=')) //Concatenate key and value with =
      .join('&') //Concatenate key-value pairs with &
  }`)
}  

But, if you want to stick to you version, here's a fixed example of it:但是,如果你想坚持你的版本,这里有一个固定的例子:

requests.get(`/wp-json/wp/v2/posts?${ppp ? `per_page=${ppp}` : ''}${(ppp && page) ? '&' : ''}${page ? `page=${page}` : ''}`)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM