在 React Router 中,除了使用 Route
组件来处理 404 错误页面,还可以借助一些编程式的方法或者结合高阶组件等手段来实现,下面针对 React Router v6 进行详细介绍。
1. 使用 useRoutes
钩子函数
useRoutes
是 React Router v6 提供的一个强大钩子,它可以让你以 JavaScript 对象的形式来定义路由配置,这种方式在处理 404 页面时同样适用。
import React from 'react';
import { BrowserRouter as Router, useRoutes } from 'react-router-dom';
// 首页组件
const Home = () => <h1>Home Page</h1>;
// 关于页面组件
const About = () => <h1>About Page</h1>;
// 404 错误页面组件
const NotFound = () => <h1>404 - Page Not Found</h1>;
const AppRoutes = () => {
const routes = useRoutes([
{ path: '/', element: <Home /> },
{ path: '/about', element: <About /> },
{ path: '*', element: <NotFound /> }
]);
return routes;
};
const App = () => {
return (
<Router>
<AppRoutes />
</Router>
);
};
export default App;
在上述代码里,useRoutes
接收一个路由配置数组,当路径不匹配前面定义的 /
和 /about
时,就会匹配 path: '*'
的路由,进而渲染 404 页面。
2. 高阶组件(HOC)封装处理
可以创建一个高阶组件来统一处理 404 错误页面,这样可以增强代码的复用性和可维护性。
import React from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
// 首页组件
const Home = () => <h1>Home Page</h1>;
// 关于页面组件
const About = () => <h1>About Page</h1>;
// 404 错误页面组件
const NotFound = () => <h1>404 - Page Not Found</h1>;
// 高阶组件,用于包裹 Routes 并处理 404
const withNotFound = (WrappedComponent) => {
return () => {
return (
<Routes>
<Route path="*" element={<NotFound />} />
<Route element={<WrappedComponent />} />
</Routes>
);
};
};
const AppRoutes = () => {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
);
};
const AppWithNotFound = withNotFound(AppRoutes);
const App = () => {
return (
<Router>
<AppWithNotFound />
</Router>
);
};
export default App;
这里定义了 withNotFound
高阶组件,它会在包裹的 Routes
前面添加一个 path="*"
的路由来处理 404 情况。
3. 结合 useLocation
和状态管理
可以结合 useLocation
钩子和状态管理(如 React 的 useState
)来手动判断路径是否匹配,进而决定是否渲染 404 页面。
import React, { useState } from 'react';
import { BrowserRouter as Router, Routes, Route, useLocation } from 'react-router-dom';
// 首页组件
const Home = () => <h1>Home Page</h1>;
// 关于页面组件
const About = () => <h1>About Page</h1>;
// 404 错误页面组件
const NotFound = () => <h1>404 - Page Not Found</h1>;
const App = () => {
const location = useLocation();
const [isNotFound, setIsNotFound] = useState(false);
const validPaths = ['/', '/about'];
if (!validPaths.some(path => location.pathname === path)) {
setIsNotFound(true);
}
return (
<Router>
{isNotFound ? <NotFound /> : (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
)}
</Router>
);
};
export default App;
在这个例子中,使用 useLocation
获取当前路径,通过和有效路径数组进行比较,如果不匹配则设置 isNotFound
状态为 true
,从而渲染 404 页面。不过这种方法相对复杂,一般不常用,仅作拓展思路参考。