简体   繁体   English

矩形 | 从 url 中获取参数值,省略 null 值

[英]RectJs | Get a parameter value from url omitting null values

Can someone please help me with this?有人可以帮我吗? I am getting "fruit" parameter's value from the URL in reactJs.我从 reactJs 中的 URL 获得“水果”参数的值。 As for example, if My URL is like:例如,如果我的 URL 是这样的:

http://localhost:3001/buy?fruit=&fruit=1&fruit=&fruit= http://localhost:3001/buy?fruit=&fruit=1&fruit=&fruit=

any one of these four "fruit" parameter can contain the value.这四个“fruit”参数中的任何一个都可以包含该值。 (only one have a value.)(here the second parameter contains the value, it depends on the clients preference. ) (只有一个有值。)(这里第二个参数包含值,这取决于客户的偏好。)

it can be either, http://localhost:3001/buy?fruit=1&fruit=&fruit=&fruit=(here the first parameter has the value) http://localhost:3001/buy?fruit=&fruit=&fruit=1&fruit= (here the third parameter has the value) http://localhost:3001/buy?fruit=&fruit=&fruit=&fruit=1 (here the fort parameter has the value.)可以是 http://localhost:3001/buy?fruit=1&fruit=&fruit=&fruit=(这里第一个参数有值) http://localhost:3001/buy?fruit=&fruit=&fruit=1&fruit= (这里第三个参数有值) http://localhost:3001/buy?fruit=&fruit=&fruit=&fruit=1 (这里fort参数有值。)

The URL has some null values as I have pre from inputs which are null. URL 有一些 null 值,因为我有来自 null 的输入。

How to omit these null values and get the parameter value?如何省略这些 null 值并获取参数值?

here's the code segment where I get data from URL:这是我从 URL 获取数据的代码段:

let myfruit = (new URLSearchParams(window.location.search)).get("fruit")

this returns null value and not the parameter value.这将返回 null 值而不是参数值。

How can I get this done?我怎样才能完成这项工作?

I personally have used URL searchParams我个人用过 URL searchParams

let url = new URL('http://localhost:3001/buy?fruit=&fruit=1&fruit=&fruit=')
let fruitParam = url.searchParams.getAll('fruit').filter(x => x) 

The .filter bit is optional to remove null values. .filter位是可选的,用于删除 null 值。

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

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