本文介绍了URLSearchParams抛出空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我今天面临着一件奇怪的事情.我曾经使用URLSearchParams()
从URL中提取搜索参数.但是,今天,在我的React应用程序中,当我按以下方式使用它时,它完全停止了工作.为什么params
在这里是空对象?任何有用的建议都将受到高度赞赏.
I'm facing a strange thing today. I used to use URLSearchParams()
to extract the search params out of the URL. However, today, in my React app, it stopped working altogether when I used it as follows. Why params
is an empty object here? any helpful advise is highly appreciated.
// url of the web page is **http://localhost:3000/reset-password/?token=sks-4e5r-sklks-io**
useEffect(() => {
console.log(window.location.search) // output -> ?token=sks-4e5r-sklks-io
const params = new URLSearchParams(window.location.search);
console.log(params) // output -> {}
})
推荐答案
使用new URL()
启用search
将 URLSearchParams 与get()
一起使用获取参数
const url = new URL(window.location);
const params = new URLSearchParams(url.search);
params.get("token")
您可以通过以下示例进行尝试:
You can try it via this sample:
const App = () => {
const url = new URL(
"http://localhost:3000/reset-password/?token=sks-4e5r-sklks-io"
);
// const url = new URL(window.location);
const params = new URLSearchParams(url.search);
console.log(params.get("token"));
return <div className="App"></div>
}
ReactDOM.render(<App />, document.getElementById("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.12.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.12.0/umd/react-dom.production.min.js"></script>
这篇关于URLSearchParams抛出空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!