我有一条路线
<Route path="/search/:slug"><SearchPage /></Route>
在我的 React 路由器中。 SearchPage 是一个使用 useParams()
的组件。 Hook 由 react-router-dom
提供.// SearchPage.js
import React from 'react';
import { useParams } from 'react-router-dom';
export function SearchPage(props) {
const { slug } = useParams();
console.log(slug)
// ...do other stuff
}
但是,当我导航到 /search/foo#bar
时,SearchPage组件只接收foo
在 slug
.我的组件有可能收到完整的 foo#bar
,或者更好的是,foo
和 bar
分别地?
最佳答案
您需要使用 useLocation
Hook 并获取 hash
从那里。第一步是导入useLocation
来自 react-router-dom
:
import useLocation from "react-router-dom";
在组件函数中,使用这个:const { hash } = useLocation();
来自 docs :
The
useLocation
hook returns thelocation
object that represents the current URL. You can think about it like auseState
that returns a newlocation
whenever the URL changes.This could be really useful e.g. in a situation where you would like to trigger a new “page view” event using your web analytics tool whenever a new page loads
关于reactjs - 如何使用 React Router 和 useParams 钩子(Hook)在散列(#)之后检索参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65404167/