【问题标题】:How to retrieve the parameter after a hash (#) with React Router and useParams hook?如何使用 React Router 和 useParams 挂钩在哈希 (#) 后检索参数?
【发布时间】:2020-12-22 06:32:40
【问题描述】:

我有一条类似的路线

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

在我的 React 路由器中。 SearchPage 是一个使用react-router-dom 提供的useParams() 钩子的组件。

// 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 组件仅在slug 中接收foo。我的组件可以接收完整的foo#bar,或者更好的是,分别接收foobar

【问题讨论】:

  • 我认为来自react-router-domuseLocation 钩子。类似const {hash} = useLocation()

标签: reactjs react-router-dom


【解决方案1】:

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

import useLocation from "react-router-dom";

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

const { hash } = useLocation();

来自docs

useLocation

useLocation 挂钩返回代表当前 URL 的 location 对象。你可以把它想象成一个useState,只要 URL 发生变化,它就会返回一个新的location

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

【讨论】:

    【解决方案2】:

    在这样的网址中:“/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-06-16
      • 2021-05-06
      • 1970-01-01
      • 2020-09-13
      • 2020-07-13
      • 1970-01-01
      • 1970-01-01
      • 2021-04-20
      • 2021-05-12
      相关资源
      最近更新 更多