介紹
歡迎來到我們關(guān)于 react router dom 的深入教程!如果您是一名 ui 開發(fā)人員,希望通過動態(tài)路由功能增強 react 應(yīng)用程序,那么您來對地方了。 react router dom 是一個功能強大的庫,允許您創(chuàng)建具有多個視圖的單頁面應(yīng)用程序,同時保持流暢、無縫的用戶體驗。
在這份綜合指南中,我們將引導(dǎo)您了解有關(guān) react router dom 所需了解的所有內(nèi)容,從基本概念到高級技術(shù)。無論您是 react 新手還是希望提高技能的經(jīng)驗豐富的開發(fā)人員,本教程都將為您提供在 react 應(yīng)用程序中有效實現(xiàn)路由所需的知識和實際示例。
那么,讓我們一起深入探索 react router dom 的世界吧!
react router dom 入門
什么是 react router dom?
react router dom 是 react 應(yīng)用程序的流行路由庫。它允許您在單頁應(yīng)用程序 (spa) 中創(chuàng)建動態(tài)的客戶端路由。使用 react router dom,您可以根據(jù)當(dāng)前 url 輕松管理不同的視圖和組件,為您的用戶提供無縫的導(dǎo)航體驗。
安裝 react router dom
開始在 react 應(yīng)用程序中實現(xiàn)路由之前,我們需要安裝 react router dom 包。打開終端并導(dǎo)航到項目目錄,然后運行以下命令:
npm install react-router-dom
登錄后復(fù)制
這將在您的項目中安裝最新版本的 react router dom。
基本設(shè)置
要開始在應(yīng)用程序中使用 react router dom,您需要導(dǎo)入必要的組件并使用 browserrouter 組件包裝主應(yīng)用程序組件。以下是如何在 index.js 文件中設(shè)置 react router dom 的基本示例:
import react from 'react';
import reactdom from 'react-dom';
import { browserrouter } from 'react-router-dom';
import app from './app';
reactdom.render(
<browserrouter><app></app></browserrouter>,
document.getelementbyid('root')
);
登錄后復(fù)制
現(xiàn)在我們已經(jīng)完成了基本設(shè)置,讓我們探索 react router dom 的核心組件以及如何有效地使用它們。
react router dom 的核心組件
路線與路線
路由和路由組件是 react router dom 的構(gòu)建塊。它們允許您定義應(yīng)為應(yīng)用程序中的每個路線呈現(xiàn)的不同路徑和組件。
這是如何使用這些組件的示例:
import react from 'react';
import { routes, route } from 'react-router-dom';
import home from './components/home';
import about from './components/about';
import contact from './components/contact';
function app() {
return (
<routes><route path="/" element="{<home"></route>} />
<route path="/about" element="{<about"></route>} />
<route path="/contact" element="{<contact"></route>} />
</routes>
);
}
export default app;
登錄后復(fù)制
在此示例中,我們定義了三個路由:主頁(“/”)、關(guān)于頁面(“/about”)和聯(lián)系頁面(“/contact”)。每個路由都與一個特定的組件相關(guān)聯(lián),當(dāng)訪問相應(yīng)的 url 時,該組件將被渲染。
鏈接組件
link 組件用于在應(yīng)用程序中創(chuàng)建導(dǎo)航鏈接。它是 react router dom 的重要組成部分,因為它允許用戶在不同視圖之間移動,而不會觸發(fā)整個頁面重新加載。
以下是如何使用鏈接組件:
import react from 'react';
import { link } from 'react-router-dom';
function navigation() {
return (
<nav><ul>
<li>
<link to="/">home</li>
<li>
<link to="/about">about</li>
<li>
<link to="/contact">contact</li>
</ul></nav>
);
}
export default navigation;
登錄后復(fù)制
導(dǎo)航鏈接組件
navlink 組件與 link 類似,但它提供了用于設(shè)置活動鏈接樣式的附加功能。這對于創(chuàng)建要突出顯示當(dāng)前活動頁面的導(dǎo)航菜單特別有用。
這是如何使用 navlink 的示例:
import react from 'react';
import { navlink } from 'react-router-dom';
function navigation() {
return (
<nav><ul>
<li>
<navlink to="/" style="{({" isactive> isactive ? { color: 'red' } : undefined}>
home
</navlink>
</li>
<li>
<navlink to="/about" style="{({" isactive> isactive ? { color: 'red' } : undefined}>
about
</navlink>
</li>
<li>
<navlink to="/contact" style="{({" isactive> isactive ? { color: 'red' } : undefined}>
contact
</navlink>
</li>
</ul></nav>
);
}
export default navigation;
登錄后復(fù)制
在此示例中,我們使用 isactive 屬性將紅色應(yīng)用于活動鏈接。
高級路由技術(shù)
現(xiàn)在我們已經(jīng)介紹了基礎(chǔ)知識,讓我們探索一些可以使用 react router dom 實現(xiàn)的更高級的路由技術(shù)。
嵌套路由
嵌套路由允許您在應(yīng)用程序中創(chuàng)建更復(fù)雜的路由結(jié)構(gòu)。這對于使用共享組件創(chuàng)建布局或組織相關(guān)路線特別有用。
這是如何實現(xiàn)嵌套路由的示例:
import react from 'react';
import { routes, route, outlet } from 'react-router-dom';
import header from './components/header';
import footer from './components/footer';
import home from './components/home';
import about from './components/about';
import services from './components/services';
import servicedetails from './components/servicedetails';
function layout() {
return (
<div>
<header></header><outlet></outlet><footer></footer>
</div>
);
}
function app() {
return (
<routes><route path="/" element="{<layout"></route>}>
<route index element="{<home"></route>} />
<route path="about" element="{<about"></route>} />
<route path="services" element="{<services"></route>} />
<route path="services/:id" element="{<servicedetails"></route>} />
</routes>
);
}
export default app;
登錄后復(fù)制
在此示例中,我們創(chuàng)建了一個包含頁眉和頁腳的布局組件。 outlet 組件用于渲染布局內(nèi)的子路由。
動態(tài)路由和 url 參數(shù)
動態(tài)路線允許您創(chuàng)建可以處理可變路段的靈活路徑。這對于需要顯示特定項目的詳細(xì)信息(例如產(chǎn)品頁面或用戶個人資料)的場景非常有用。
以下是如何使用動態(tài)路由和訪問 url 參數(shù)的示例:
import react from 'react';
import { useparams } from 'react-router-dom';
function productdetails() {
const { productid } = useparams();
return (
<div>
<h1>product details</h1>
<p>you are viewing product with id: {productid}</p>
</div>
);
}
export default productdetails;
登錄后復(fù)制
要使用此組件,您需要定義如下路由:
<route path="/products/:productid" element="{<productdetails"></route>} />
登錄后復(fù)制
程序化導(dǎo)航
有時您需要根據(jù)某些條件或用戶操作以編程方式進(jìn)行導(dǎo)航。 react router dom 為此提供了 usenavigate 鉤子。
這是如何使用 usenavigate 的示例:
import react from 'react';
import { usenavigate } from 'react-router-dom';
function loginform() {
const navigate = usenavigate();
const handlesubmit = (event) => {
event.preventdefault();
// perform login logic here
// if login is successful, navigate to the dashboard
navigate('/dashboard');
};
return (
登錄后復(fù)制
{/* form fields */}
);
}
export default loginform;
處理路由參數(shù)和查詢字符串
react router dom 提供了強大的工具來處理路由參數(shù)和查詢字符串,允許您創(chuàng)建動態(tài)且靈活的路由解決方案。
路由參數(shù)
我們已經(jīng)了解了如何通過 useparams 鉤子使用路由參數(shù)。讓我們通過一個更復(fù)雜的示例進(jìn)一步探討這一點:
import react from 'react';
import { useparams } from 'react-router-dom';
function blogpost() {
const { category, postid } = useparams();
return (
<div>
<h1>blog post</h1>
<p>category: {category}</p>
<p>post id: {postid}</p>
</div>
);
}
export default blogpost;
登錄后復(fù)制
要使用此組件,您需要定義如下路由:
<route path="/blog/:category/:postid" element="{<blogpost"></route>} />
登錄后復(fù)制
這允許您創(chuàng)建像 /blog/technology/123 或 /blog/travel/456 這樣的 url,并從 url 中動態(tài)提取類別和帖子 id。
查詢字符串
查詢字符串對于將可選參數(shù)傳遞給路由非常有用。 react router dom 提供了 usesearchparams 鉤子來處理查詢字符串。
這是如何使用 usesearchparams 的示例:
import react from 'react';
import { usesearchparams } from 'react-router-dom';
function productlist() {
const [searchparams, setsearchparams] = usesearchparams();
const category = searchparams.get('category');
const sortby = searchparams.get('sortby');
return (
<div>
<h1>product list</h1>
<p>category: {category || 'all'}</p>
<p>sort by: {sortby || 'default'}</p>
<button onclick="{()"> setsearchparams({ category: 'electronics', sortby: 'price' })}>
filter electronics, sort by price
</button>
</div>
);
}
export default productlist;
登錄后復(fù)制
在此示例中,我們從查詢字符串中讀取類別和排序參數(shù)。我們還演示了如何使用 setsearchparams 函數(shù)更新查詢字符串。
保護(hù)路由并處理身份驗證
許多應(yīng)用程序中的一個常見要求是根據(jù)用戶身份驗證狀態(tài)保護(hù)某些路由。 react router dom 可以與您的身份驗證邏輯結(jié)合使用來創(chuàng)建受保護(hù)的路由。
這是如何實現(xiàn)受保護(hù)路由的示例:
import react from 'react';
import { route, navigate } from 'react-router-dom';
function protectedroute({ element, isauthenticated, ...rest }) {
return (
<route element="{isauthenticated" : to="/login" replace></route>}
/>
);
}
function app() {
const [isauthenticated, setisauthenticated] = react.usestate(false);
return (
<routes><route path="/" element="{<home"></route>} />
<route path="/login" element="{<login" setisauthenticated="{setisauthenticated}"></route>} />
<protectedroute path="/dashboard" element="{<dashboard"></protectedroute>}
isauthenticated={isauthenticated}
/>
</routes>
);
}
export default app;
登錄后復(fù)制
在此示例中,我們創(chuàng)建了一個 protectedroute 組件來檢查用戶是否經(jīng)過身份驗證。如果是,則渲染指定的元素;如果沒有,它會將他們重定向到登錄頁面。
處理 404 頁面和重定向
react router dom 可以輕松處理 404(未找到)頁面并在必要時實現(xiàn)重定向。
404 頁
要創(chuàng)建 404 頁面,您可以在路由定義末尾使用 * 路徑:
import react from 'react';
import { routes, route } from 'react-router-dom';
import home from './components/home';
import about from './components/about';
import notfound from './components/notfound';
function app() {
return (
<routes><route path="/" element="{<home"></route>} />
<route path="/about" element="{<about"></route>} />
<route path="*" element="{<notfound"></route>} />
</routes>
);
}
export default app;
登錄后復(fù)制
在此示例中,將為任何與定義的路徑不匹配的路線渲染 notfound 組件。
重定向
有時您可能需要將用戶從一條路線重定向到另一條路線。 react router dom 為此提供了 navigate 組件:
import react from 'react';
import { routes, route, navigate } from 'react-router-dom';
import home from './components/home';
import oldpage from './components/oldpage';
import newpage from './components/newpage';
function app() {
return (
<routes><route path="/" element="{<home"></route>} />
<route path="/old-page" element="{<navigate" to="/new-page" replace></route>} />
<route path="/new-page" element="{<newpage"></route>} />
</routes>
);
}
export default app;
登錄后復(fù)制
在此示例中,任何嘗試訪問 /old-page 的用戶都會自動重定向到 /new-page。
通過代碼分割優(yōu)化性能
隨著應(yīng)用程序的增長,您可能希望實現(xiàn)代碼分割以提高性能。 react router dom 與 react 的延遲加載功能配合得很好,允許您僅在需要時加載路由組件。
以下是如何使用 react router dom 實現(xiàn)代碼分割的示例:
import React, { Suspense, lazy } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./components/Home'));
const About = lazy(() => import('./components/About'));
const Contact = lazy(() => import('./components/Contact'));
function App() {
return (
<suspense fallback="{<div">Loading...}>
<routes><route path="/" element="{<Home"></route>} />
<route path="/about" element="{<About"></route>} />
<route path="/contact" element="{<Contact"></route>} />
</routes></suspense>
);
}
export default App;
In this example, we're using React's `lazy` function to dynamically import our components. The `Suspense` component is used to show a loading indicator while the component is being loaded.
登錄后復(fù)制
結(jié)論
恭喜!您現(xiàn)在已經(jīng)完成了有關(guān) react router dom 的綜合教程。我們涵蓋了從基本設(shè)置到嵌套路由、動態(tài)路由、身份驗證和代碼分割等高級技術(shù)的所有內(nèi)容。有了這些知識,您就可以在 react 應(yīng)用程序中實現(xiàn)強大的路由解決方案了。
記住,掌握 react router dom 的關(guān)鍵是練習(xí)。嘗試在您自己的項目中實現(xiàn)這些概念,并且不要害怕嘗試不同的路由結(jié)構(gòu)和技術(shù)。隨著您對 react router dom 越來越熟悉,您會發(fā)現(xiàn)它為創(chuàng)建動態(tài)且用戶友好的 web 應(yīng)用程序開辟了新的可能性。






