react-router:useHistory、useLocation 和 useParams

2025-06-07

react-router:useHistory、useLocation 和 useParams

介绍

相信你已经读过我之前的博客,所以你已经知道这三个路由属性是什么了。如果你还不了解,可以在这里查看我之前的博客。我讨论了如何传递这三个路由属性,并且想向你展示另一种更简单的方法来访问它们,而无需考虑将其作为属性传递。

使用历史

基本上,这个钩子让你可以访问history对象,并且可以使用一些函数来导航你的页面。一切都是为了导航。这就是你的使用方法useHistory

import { useHistory } from 'react-router-dom';

const Portfolio = (props) => {
    const history = useHistory();
    console.log(history);

    return (
        <div>
            Portfolio
        </div>
    );
};

export default Portfolio;
Enter fullscreen mode Exit fullscreen mode

历史里面有什么?

历史对象

好吧……这里有很多东西。我知道一开始可能会让人困惑。我会解释一下这些属性最常见的用途。

  • length(数字):您访问的页面的长度。
  • 操作(字符串):(POP,PUSH,REPLACE)
    • POP:通过url访问路线,使用history go函数history.goBack(),,history.goForward()history.go()
    • 推:使用history.push()
    • 替换:使用history.replace()
  • .push(pathname: string, state: any)/(location: object):将路径或位置推送到历史记录堆栈。推送有多种使用方法,我将在下面展示一些示例。
    //using pathname
    history.push("/blog");
    //https://localhost:3000/blogs

    //using pathname and state
    history.push("/blog", { fromPopup: true });
    //https://localhost:3000/blogs

    //using location
      history.push({
      pathname: "/blogs",
      search: "?id=5",
      hash: "#react",
      state: { fromPopup: true }
    });
    // https://localhost:3000/blogs?id=5#react
Enter fullscreen mode Exit fullscreen mode

我以前从未使用过状态。不过,在阅读了文档之后,它给了我一些启发。例如,如果你想知道用户来自哪里,就可以利用状态。

  • .replace(pathname: string, state: any)/(location: object):这基本上与 push 类似,但它会删除现有历史记录并更新为新的历史记录。此后,每当用户在浏览器中点击“返回”时.replace,它都不会返回到上一个历史记录。
  • .goBack():返回上一个历史记录。
  • .goForward():前进到上一个历史记录。
  • .go(delta: number):移动到不同的索引,并可以指定从该位置起有多少个索引(可以是负数或正数)

我从来没有使用过three.go函数,但我只是想让你知道这个函数在历史上存在过

我还准备了codesandbox来帮助您理解。

使用位置

简而言之,这就像一个始终返回当前 URL 的状态。如果 URL 发生变化, useLocation 也会更新。

里面的位置是什么?

使用位置

useLocation 不具备类似 useHistory 的任何功能,它只是用于获取有关当前 URL 的信息。

.push我将在示例中使用我们尝试从历史记录中使用的先前链接localhost:3000/blogs?id=5#react

从该 URL,如果我们尝试调用 useLocation,我们将获得该对象。

uselocation2

只要记住目的useLocation()是从当前路线获取信息,它将返回这些属性。

{
  key: 'ac3df4', // not with HashHistory!
  pathname: '/somewhere',
  search: '?some=search-string',
  hash: '#howdy',
  state: {
    [userDefined]: true
  }
}
Enter fullscreen mode Exit fullscreen mode

useParams

这是 React-router 中最容易理解的钩子。每当调用此钩子时,你都会得到一个将所有参数存储为属性的对象。

您只需要这一行代码就可以访问您的参数。

const params = useParams();
Enter fullscreen mode Exit fullscreen mode

你可以在我的 CodeSandBox 中玩一下

结论

我希望这篇文章能帮助你理解 React-router 的三个主要实用钩子。一开始可能会有点困惑,但经过一番尝试之后,一切都变得清晰易懂了。祝你玩得开心!欢迎在评论区留言提问。

文章来源:https://dev.to/raaynaldo/react-router-usehistory-uselocation-and-useparams-10cd
PREV
📚 Redux Toolkit 设置教程 Redux Toolkit 教程
NEXT
为 Shopify 主题开发设置本地环境