reactjs - 如何使用 React Router 和 useParams 钩子(Hook)在散列(#)之后检索参数?

标签 reactjs react-router-dom

我有一条路线

<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组件只接收fooslug .我的组件有可能收到完整的 foo#bar ,或者更好的是,foobar分别地?

最佳答案

您需要使用 useLocation Hook 并获取 hash从那里。第一步是导入useLocation来自 react-router-dom :

import useLocation from "react-router-dom";
在组件函数中,使用这个:
const { hash } = useLocation();

来自 docs :

useLocation

The useLocation hook returns the location object that represents the current URL. You can think about it like a useState that returns a new location 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/

相关文章:

javascript - 如何使用 webview 为 VSCode 扩展实现 React App 导航

javascript - Socket.io 连接完好无损,但从不卸载的 React 组件在页面导航后变得对套接字事件无响应

reactjs - 获取React组件的类型propTypes定义

javascript - 从reactJS中的json响应创建动态表

css - Ant design v4 中如何动态切换主题?

jestjs - react Jest 模拟 useNavigate()

javascript - 为什么 React-Router-Dom 的 Router 中需要 'history'?

reactjs - 无法在 react 路由器dom中使用链接传递 Prop

javascript - 源有 2 个元素,但目标只允许 1 个。Typescript 扩展运算符

javascript - 即使在 React 中正确导入后也不包含默认导出