问题
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