4

I have a route like

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

in my React Router. SearchPage is a component that uses the useParams() hook provided by 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
}

However, when I navigate to /search/foo#bar, the SearchPage component only receives foo in the slug. It is possible for my component to receive the full foo#bar, or, better yet, foo and bar separately?

4

2 回答 2

4

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

import useLocation from "react-router-dom";

在组件函数中,使用这个:

const { hash } = useLocation();

文档

useLocation

useLocation钩子返回location表示当前 URL 的对象。您可以将其视为每当 URL 更改时useState返回一个新的。location

这可能非常有用,例如在您希望在新页面加载时使用您的网络分析工具触发新的“页面查看”事件的情况

于 2020-12-22T07:02:39.737 回答
0

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

React 为这个“useLocation”提供了一个钩子。使用 Location 将为您提供一个包含 4 件事的对象,但对于此示例,您只需要担心 3 个,(“路径名”:“/myUrl/products/product12”、“搜索”:“myQuery=12”、“哈希” :“我的哈希”)

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;
于 2022-02-28T14:57:12.770 回答