网址: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
}
输出:
name: netflix
url: https://localhost?apikey=123
如您所见,code
参数丢失了。我预计 url
参数的值应为 https://localhost?apikey=123&code=321
。
软件包版本:
"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;
}
关于javascript - 如何解析url查询字符串中的完整链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67156570/