如何使用 React Router 和 useParams hook 检索哈希(#)后的参数?

问题描述 投票:0回答:3

我有一条类似的路线

<Route path="/search/:slug"><SearchPage /></Route>

在我的 React Router 中。 SearchPage 是一个使用

useParams()
提供的
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

reactjs react-router-dom
3个回答
20
投票

您需要使用

useLocation
钩子并从那里获取
hash
。第一步是从
useLocation
导入
react-router-dom
:

import useLocation from "react-router-dom";

在组件函数内部,使用这个:

const { hash } = useLocation();

来自文档

useLocation

useLocation
钩子返回表示当前 URL 的
location
对象。您可以将其想象为
useState
,只要 URL 更改,它就会返回新的
location

这可能非常有用,例如当您希望在每次加载新页面时使用网络分析工具触发新的“页面视图”事件


0
投票

在这样的 URL 中:“/myUrl/products/product12?myQuery=12#myHash” UseParams 将返回查询之前的所有内容,例如“/myUrl/products/product12”,但不会返回查询“?myQuery=12#myHash”。

React 有一个针对这个“useLocation”的钩子。使用位置将为您提供一个包含 4 件事的对象,但在本例中您只需要担心 3 件事,( “路径名”:“/myUrl/products/product12”, “搜索”:“myQuery = 12”, “哈希”:“myHash”)

import { useLocation } from 'react-router-dom';
const QueryDetails = () => {
    const location = useLocation();
    const myQuery  = location.search;

return (
        <div className='container mt-2'>
           <p>{myQuery}</p>
        </div>
    );
}
 
export default QueryDetails;

0
投票

您可以使用与 url 哈希相关的名为 reach-hash-control 的非常轻的软件包来读取 url 哈希参数并在页面等的哈希值之间滚动 查看https://github.com/haseeb5555/react-hash-control(如果您觉得有帮助,请给星)

© www.soinside.com 2019 - 2024. All rights reserved.