[英]How to parse the complete link in the url query string?
URL: https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321
代码:
import { useLocation } from "react-router-dom";
function useQuery() {
const {search} = useLocation();
const query = new URLSearchParams(search);
console.log('name: ', query.get('name'))
console.log('url: ', query.get('url'))
return query
}
Output:
name: netflix
url: https://localhost?apikey=123
如您所见, code
参数丢失了。 我希望url
参数的值应该是https://localhost?apikey=123&code=321
。
package 版本:
"react-router-dom": "5.2.0"
发生这种情况是因为您没有对 URI 组件进行编码。 您可以使用encodeURIComponent
和decodeURIComponent
函数来解决您的问题。 在推送到路由之前编码 URL 并在接收后您可以对其进行解码。
注意:请考虑不需要解码,因为new URLSearchParams(search).get('key')
命令会自动解码组件。
// In navigating component
const history = useHistory();
return (
...
<button onClick={() => history.push(`/?name=netflix&url=${encodeURIComponent('https://localhost?apikey=123&code=321')}`)}>
Go to link
</button>
...
)
import { useLocation } from "react-router-dom";
function useQuery() {
const {search} = useLocation();
const query = new URLSearchParams(search);
console.log('name: ', query.get('name')) // name: netflix
console.log('url: ', query.get('url')) // url: https://localhost?apikey=123&code=321
return query;
}
您的代码是正确的,但您的输入 URL 是错误的。
如果您使用:
https://n9hon.csb.app?name=netflix&url=https://localhost?apikey=123&code=321
您的浏览器会将其读取为
Protocoll
https:
Top Level Domain
.app
Domain
csb
Sub-Domain
n9hon
Params
?name=netflix&url=https://localhost?apikey=123&code=321
到目前为止还可以,但随后事情就付诸东流了:
Param 1
name=netflix
Param 2
url=https://localhost?apikey=123
Param 3
code=321
如果您想将 Param2 和 Param 3 读取为一个 Param,则需要摆脱 & (并且还要清除?:= 和 /)
https://n9hon.csb.app?name=netflix&url=https%3A%2F%2Flocalhost%3Fapikey%3D123%26amp%3Bcode%3D321
在您的代码中,您可以通过encodeURI(uri)轻松执行此操作并通过decodeURI(enc)还原它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.