URLSearchParams抛出空对象

时间:2020-03-28 12:42:44

标签: reactjs parameters

我今天面临着一件奇怪的事情。我曾经使用URLSearchParams()从URL中提取搜索参数。但是,今天,在我的React应用程序中,当我如下使用它时,它完全停止了工作。为什么params在这里是空对象?任何有益的建议都将受到高度赞赏。

// 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 个答案:

答案 0 :(得分:1)

使用new URL()启用search

URLSearchParamsget()一起使用来获取参数

const url = new URL(window.location);
const params = new URLSearchParams(url.search);
params.get("token")

您可以通过以下示例进行尝试:

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>