React根據(jù)配置生成路由的示例代碼
根據(jù)配置生成路由
React路由看似只能由Route組件包裹組件的結(jié)構(gòu)來(lái)構(gòu)成,但是其實(shí)也可以通過(guò)編寫(xiě)路由數(shù)組配置然后通過(guò)數(shù)組循環(huán)來(lái)生成Route組件包裹組件的結(jié)構(gòu)。

安裝依賴(lài)react-router-dom,這是React中用于處理路由的庫(kù)
npm install react-router-dom
創(chuàng)建路由配置
創(chuàng)建一個(gè)路由配置文件,其中定義了一個(gè)路由數(shù)組,包含各個(gè)路由的路徑、組件等信息
// src/router/index.js
const routes = [
{
path: '/', // 路由路徑
component: () => import('./views/Home'), // 路由對(duì)應(yīng)的組件
exact: true
},
{
path: '/about',
component: () => import('./views/About'),
},
{
path: '/contact',
component: () => import('./views/Contact'),
},
// 可以添加更多的路由配置...
];
export default routes;
exact 屬性用于指定路由匹配是否需要完全精確匹配路徑。當(dāng) exact 設(shè)置為 true 時(shí),只有當(dāng)URL與path屬性完全一致時(shí),對(duì)應(yīng)的路由組件才會(huì)被渲染。如果沒(méi)有設(shè)置 exact 或者設(shè)置為 false,那么只要URL包含path指定的路徑,該路由就會(huì)被認(rèn)為匹配,進(jìn)而渲染相應(yīng)的組件。
假設(shè)有以下兩個(gè)路由配置:
- Home頁(yè)面:路徑為
/ - User Profile頁(yè)面:路徑為
/user/:id
<Routes>
<Route path="/" element={<Home />} exact />
<Route path="/user/:id" element={<UserProfile />} />
</Routes>
兩個(gè)路由都是使用 exact: true時(shí):
當(dāng)訪(fǎng)問(wèn) / 時(shí),只有 Home 組件會(huì)被渲染。 當(dāng)訪(fǎng)問(wèn) /user/123 時(shí),只有 UserProfile 組件會(huì)被渲染。
不使用 exact 或 exact: false時(shí):
當(dāng)訪(fǎng)問(wèn) / 時(shí),Home 組件會(huì)被渲染。 當(dāng)訪(fǎng)問(wèn) /user/123 時(shí),由于 /user/:id 包含了 /,所以 Home 和 UserProfile 兩個(gè)組件都會(huì)被渲染。如果沒(méi)有設(shè)置 exact,React Router 認(rèn)為 / 是 /user/:id 的一部分。
通常情況下,對(duì)于首頁(yè)(通常是根路徑 /),需要使用 exact: true,以避免其他路徑(如 /user/:id)也匹配到根路徑,導(dǎo)致不必要的組件渲染。而對(duì)于其他具體的路徑,則不需要設(shè)置 exact,因?yàn)樗鼈兺ǔR呀?jīng)足夠具體,不會(huì)引起混淆。
代碼中使用了import()函數(shù)來(lái)異步加載組件,這樣就實(shí)現(xiàn)了按需加載,有助于提高應(yīng)用的性能。
也可以使用lazyHook懶加載的寫(xiě)法,如下所示:
// src/router/index.js
import React, { lazy } from 'react'
// 懶加載路由
const Home = lazy(()=>import("./views/Home"))
const About = lazy(()=>import("./views/About"))
const routes = [
{
path: '/',
component: Home
},
{
path: '/about',
component: About
},
{
path: '/contact',
component: lazy(() => import('./views/Contact')),
},
]
export default routes
動(dòng)態(tài)生成路由
在項(xiàng)目的主應(yīng)用文件(如App.jsx)中,使用react-router-dom提供的<Routes>和<Route>組件,結(jié)合上面的配置來(lái)動(dòng)態(tài)生成路由。
// src/App.jsx
import React from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';
import routes from './router/index.js';
function App() {
return (
<Router>
<Routes>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
element={<route.component />}
exact={route.exact}
/>
))}
</Routes>
</Router>
);
}
export default App;
element={<route.component />},它會(huì)根據(jù)路由數(shù)組配置中數(shù)組元素的component屬性來(lái)加載對(duì)應(yīng)的組件。
也可以在main.jsx文件中使用<Router>包裹根組件
// src/main.jsx
import React from 'react'; // 用于創(chuàng)建組件的
import { createRoot } from 'react-dom/client'; // 用于渲染頁(yè)面的
import { Provider } from 'react-redux';
import store from './store/index.js';
import App from './App.jsx';
import { BrowserRouter} from 'react-router-dom';
createRoot(document.getElementById('root')).render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
)
使用lazyHook懶加載路由組件時(shí),需要在App.js中,為所有懶加載的組件提供了一個(gè)錯(cuò)誤邊界或加載狀態(tài)
// src/App.jsx
import React, { Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import routes from './router/index.js';
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
{routes.map((route, index) => (
<Route
key={index}
path={route.path}
element={<route.component />}
exact={route.exact}
/>
))}
</Routes>
</Suspense>
);
}
export default App;
還可以將配置的路由數(shù)組循環(huán)動(dòng)態(tài)生成路由的代碼抽離成一個(gè)單獨(dú)的函數(shù)
// src/router/createRoute.js
import React from 'react';
import { Route } from 'react-router-dom';
// 接受一個(gè)路由數(shù)組
const createRoute = (routes) => {
return routes.map((route,index) => {
return (
<Route
key={index}
path={route.path}
element={<route.component />}
exact={route.exact}
/>
)
})
}
export default createRoute;
// src/App.jsx
import React, { Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import routes from './router/index.js';
import createRoute from './router/createRoute.js'
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Routes>
{
createRoute(routes)
}
</Routes>
</Suspense>
);
}
export default App;
配置路由中包含子路由
目錄結(jié)構(gòu):

創(chuàng)建一個(gè)路由配置文件,其中定義了各個(gè)路由及其子路由的信息,使用懶加載來(lái)優(yōu)化性能
// src/router/index.js
import React from 'react';
const routes = [
{
path: '/',
component: React.lazy(() => import('./views/Home')),
exact: true,
},
{
path: '/dashboard',
component: React.lazy(() => import('./views/Dashboard')),
children: [
{
path: 'users',
component: React.lazy(() => import('./views/Users')),
},
{
path: 'settings',
component: React.lazy(() => import('./views/Settings')),
},
],
},
{
path: '/about',
component: React.lazy(() => import('./views/About')),
},
{
path: '/contact',
component: React.lazy(() => import('./views/Contact')),
},
];
export default routes;
動(dòng)態(tài)生成路由的方法,為了處理懶加載組件的加載狀態(tài),需要添加<Suspense>組件
// src/router/createRoute.js
import React from 'react';
import { Route } from 'react-router-dom';
import { Suspense } from 'react'
const renderRoutes = (routes) => {
return routes.map((route, index) => {
// 當(dāng)前路由配置項(xiàng) route 包含 children 屬性,遞歸調(diào)用 renderRoutes 函數(shù)來(lái)處理子路由
if (route.children) {
return (
<Route
key={index}
path={route.path}
element={
<Suspense>
<route.component />
</Suspense>
}
exact={route.exact}
>
{renderRoutes(route.children)}
</Route>
);
}
return (
<Route
key={index}
path={route.path}
element={<route.component />}
exact={route.exact}
/>
);
});
};
export default renderRoutes;
// src/main.jsx
import React from 'react'; // 用于創(chuàng)建組件的
import { createRoot } from 'react-dom/client'; // 用于渲染頁(yè)面的
import { Provider } from 'react-redux';
import store from './store/index.js';
import App from './App.jsx';
import { BrowserRouter} from 'react-router-dom';
createRoot(document.getElementById('root')).render(
<Provider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</Provider>
)
// src/App.jsx
import React, { Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import routes from './router/index.js';
import renderRoutes from './router/createRoute.js'
function App() {
return (
<Suspense>
<Routes>
{
renderRoutes(routes)
}
</Routes>
</Suspense>
);
}
export default App;
為了在父組件中正確顯示子路由的內(nèi)容,需要在父組件中使用<Outlet>組件。<Outlet>組件用于渲染嵌套的子路由。
// src/views/Dashboard/index.jsx
import { Outlet,Link } from 'react-router-dom'
import React from 'react';
const Dashboard = () => {
return (
<>
<h1>Dashboard 頁(yè)面</h1>
<nav>
<ul>
<li><Link to="/dashboard/users">Users</Link></li>
<li><Link to="/dashboard/settings">Settings</Link></li>
</ul>
</nav>
<Outlet />
</>
)
}
export default Dashboard;

以上就是React根據(jù)配置生成路由的示例代碼的詳細(xì)內(nèi)容,更多關(guān)于React根據(jù)配置生成路由的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
react echarts tooltip 區(qū)域新加輸入框編輯保存數(shù)據(jù)功能
這篇文章主要介紹了react echarts tooltip 區(qū)域新加輸入框編輯保存數(shù)據(jù)功能,大概思路是用一個(gè)div包裹echarts, 然后在echarts的同級(jí)新建一個(gè)div用來(lái)用來(lái)模擬真實(shí)tooltip,通過(guò)鼠標(biāo)移入移出事件控制真實(shí)tooltip的顯示與隱藏,需要的朋友可以參考下2023-05-05
React Fiber中面試官最關(guān)心的技術(shù)話(huà)題
這篇文章主要為大家介紹了React Fiber中面試官最關(guān)心的技術(shù)話(huà)題解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06
react性能優(yōu)化useMemo與useCallback使用對(duì)比詳解
這篇文章主要為大家介紹了react性能優(yōu)化useMemo與useCallback使用對(duì)比詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
React事件處理過(guò)程中傳參的實(shí)現(xiàn)方法
這篇文章主要介紹了React事件處理過(guò)程中傳參的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧2022-10-10
React 無(wú)狀態(tài)組件(Stateless Component) 與高階組件
這篇文章主要介紹了React 無(wú)狀態(tài)組件(Stateless Component) 與高階組件,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-08-08
react-redux的connect與React.forwardRef結(jié)合ref失效的解決
這篇文章主要介紹了react-redux的connect與React.forwardRef結(jié)合ref失效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

