URLSearchParams is throwing empty object

为君一笑 提交于 2020-04-30 06:26:04

问题


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 -> {}
})

回答1:


Use new URL() to enable search

Use URLSearchParams with get() to get params

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>


来源:https://stackoverflow.com/questions/60901283/urlsearchparams-is-throwing-empty-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!