使用 React 和 History API

发布日期:2026-07-03 21:47:03   来源 : 杭州电子商务研究院    浏览量 :0
杭州电子商务研究院 发布日期:2026-07-03 21:47:03  
0

介绍

React 中的路由大量使用了 HTML5 History API。在本指南中,您将了解 History API,并构建一个简单的应用程序,以便在使用 React 路由器包时深入了解它的工作原理。

了解 History API

目前,大多数浏览器在 DOM 的 Window 对象上公开一个 history 对象,该对象用于访问浏览器的会话历史记录,并使用 history.back ()history.forward()方法(其功能也类似于浏览器中的后退和前进按钮)以及许多其他方法(如go()pushState() )向前和向后导航。您可以通过Mozilla 开发者网络 (MDN) 文档阅读有关 HTML5 History API 的更多信息

React Router 使用历史记录包,它基于浏览器历史记录 API 构建,以提供我们可以在 React 应用程序中轻松使用的界面。

历史对象具有以下属性和方法:

  • 长度 - (数字)历史堆栈中的条目数
  • action  - (字符串) 当前操作 ( PUSH、  REPLACE或 POP )
  • location  - (对象)当前位置。可能具有以下属性:
    • pathname  - (字符串) URL 的路径
    • 搜索 - (字符串) URL 查询字符串
    • hash  - (字符串) URL 哈希片段
    • state - (对象)特定位置的状态, 当此位置被推送到堆栈时 提供给 push(path, state) 。仅在浏览器和内存历史记录中可用。
  • push(path,[state])  -(函数)将新条目推送到历史堆栈
  • replace(path,[state])  -(函数)替换历史堆栈上的当前条目
  • go(n)  - (函数) 将历史堆栈中的指针移动 n 个 条目
  • goBack()  - (函数) 相当于 go(-1)
  • goForward()  - (函数) 相当于 go(1)
  • block(prompt)  -(功能)阻止导航

来自React Router 文档

设置开发环境

设置您的环境以构建一个简单的应用程序,该应用程序充当虚拟浏览器,并具有一个小型分析解决方案来显示用户来自哪些页面。您可以在本地计算机上使用create-react-app ,也可以在浏览器中输入react.new以通过codesandbox.io获得完全配置的 react 环境

接下来,使用以下命令在终端中添加react-router作为依赖项:

      yarn add react-router-dom
    

设置呈现简单基于文本的组件的虚拟页面和路由。

      import React from "react";

function HomePage() {
    return <p>Welcome Home</p>;
}
function About() {
    return <p>About Page</p>;
}
function Contact() {
    return <p>Contact Page</p>;
}
function Foo() {
    return <p>Contact Bar</p>;
}

export {HomePage, About, Contact, Foo};
    
      # Routes
import React from "react";
import { Route, Switch , BrowserRouter as Router} from "react-router-dom";
import { HomePage, About, Contact, Foo } from "./Pages/Homepage";
import "./global.css";

const Routes = () => {
    return (
				<Router>
            <Switch>
                <Route exact path="/" component={HomePage} />
				</Router>
        </div>
    );
};

export default Routes;
    

useHistory 钩子

React Router 有一个useHistory钩子,它提供了一个历史记录接口,我们可以轻松地使用它进行路由。向这些页面添加按钮(如下所示),以使用 History API 添加路由。

      import React from "react";
import { useHistory } from "react-router-dom";

function HomePage() {
    const history = useHistory();

    return (
        <>
            <button
                onClick={() => history.push("/about", { from: "HomePage" })}
            >
                About
            </button>
            <button
                onClick={() => history.push("/contact", { from: "HomePage" })}
            >
                Contact
            </button>
            <p>Welcome Home</p>
        </>
    );
}
function About({ location }) {
    const history = useHistory();
    return (
        <>
            <p>About Page </p>
            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>
            <p> You were redirected from {location.state.from}</p>
        </>
    );
}
function Contact({ location }) {
    const history = useHistory();
    return (
        <>
            <p>Contact Page</p>
            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>
            <p>You were redirected from {location.state.from}</p>
        </>
    );
}
    

上面的代码片段使用goBack()方法模拟浏览器中的后退按钮,并使用push()方法移动到新路由。push()方法也接受一个 state 对象以及from作为属性。

      import React from "react";

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

function HomePage() {
    const history = useHistory();

    return (
        <>
            <button
                onClick={() => history.push("/about", { from: "HomePage" })}
            >
                About
            </button>

            <button
                onClick={() => history.push("/contact", { from: "HomePage" })}
            >
                Contact
            </button>

            <p>Welcome Home</p>
        </>
    );
}

function About({ location }) {
    const history = useHistory();

    console.log(history);

    return (
        <>
            <p>About Page </p>

            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>

            <p> You were redirected from {location.state.from}</p>
        </>
    );
}

function Contact({ location }) {
    const history = useHistory();

    return (
        <>
            <p>Contact Page</p>

            <button
                onClick={() => {
                    history.goBack();
                }}
            >
                Go back
            </button>

            <p>You were redirected from {location.state.from}</p>
        </>
    );
}
    

结论

您已成功掌握了通过 React Router 使用 History API 的基础知识。您可以通过文档阅读有关 React Router 的更多信息您也可以通过 Twitter 与我联系,我的账号是@DesmondNyamador

了解更多

探索 Pluralsight 的这些 React 课程以继续学习:

以上内容来自杭州电子商务研究院推送
关注
关于我们
热门推荐
合作伙伴
免责声明:本站部分资讯来源于网络,如有侵权请及时联系客服,我们将尽快处理
Copyright © 2025-2027 ToB产业网址导航 公安备案 浙公网安备33010602013138号 浙ICP备16025413号-9
支持 反馈 关注 数据