如何使用React Router处理404错误页面?

在使用 React Router 时,可以通过设置一个特殊的路由来处理 404 错误页面。通常,404 页面用于显示用户访问的路径不存在时的提示信息。以下是实现步骤:

1. 创建 404 组件

首先,创建一个简单的 404 组件。例如,命名为 NotFound.js

jsx 复制代码
// NotFound.js
import React from 'react';

const NotFound = () => {
  return (
    <div>
      <h1>404 - 页面未找到</h1>
      <p>抱歉,您访问的页面不存在。</p>
    </div>
  );
};

export default NotFound;

2. 在路由中添加 404 路由

在你的主应用组件中,使用 Switch 组件来设置路由。将 NotFound 组件作为最后一个 Route,这样它会在没有其他路由匹配时渲染。

jsx 复制代码
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './Home';
import About from './About';
import NotFound from './NotFound';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/" exact component={Home} />
        <Route path="/about" component={About} />
        {/* 404 路由 */}
        <Route component={NotFound} />
      </Switch>
    </Router>
  );
};

export default App;

3. 注意路由顺序

确保 NotFound 路由放在其他路由之后,因为 Switch 会按照顺序匹配路由。第一个匹配的路由会被渲染,因此 NotFound 需要放在最后。

4. 测试 404 页面

现在,你可以尝试访问一个不存在的路径,例如 /not-existing-path,你应该会看到 404 页面。

总结

通过以上步骤,你可以轻松地处理 React Router 中的 404 错误页面。当用户访问的路径没有相应的组件时,NotFound 组件会被渲染,提供友好的提示。

相关推荐
kyriewen111 小时前
你点的“刷新”是假刷新?前端路由的瞒天过海术
开发语言·前端·javascript·ecmascript·html5
Timer@3 小时前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
阿珊和她的猫3 小时前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
skywalk81633 小时前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
RopenYuan5 小时前
FastAPI -API Router的应用
前端·网络·python
走粥5 小时前
clsx和twMerge解决CSS类名冲突问题
前端·css
Purgatory0016 小时前
layui select重新渲染
前端·layui
weixin199701080166 小时前
《中国供应商商品详情页前端性能优化实战》
前端·性能优化
九皇叔叔7 小时前
003-SpringSecurity-Demo 统一响应类
java·javascript·spring·springsecurity