如何使用 React-Router 在 React 中正确渲染 404 页面? [英] How to properly render a 404 page in React with React-Router?
问题描述
我正在使用 React 和 React-Router 构建一个网站,我想在用户访问不存在的 url 时呈现 404 页面.
有些网址是动态的,比如,
www.site.com/user/(用户名)
如果具有特定用户名的用户不存在,如何使用 react-router 呈现 404 页面?我是否必须在 API 调用期间在组件本身中手动编写代码以检查用户是否存在,然后将用户重定向到 404 组件?
我正在寻找将用户重定向到未找到页面的最佳方式.寻找有关如何做到最好的想法.
使用切换然后重定向
https://reacttraining.com/react-router/web/example/不匹配
https://reacttraining.com/react-router/web/api/Redirect
有效 URL 无重定向:/user/valid_username
404 URL 重定向:/user/invalid_username
import React, { Component } from 'react'import { BrowserRouter as Router, Route, Switch, Redirect } from 'react-router-dom'类 App 扩展组件 {使成为() {返回 (<路由器><div><开关><Route path="/user/:username" component={Child}/><Route path="/404" component={NoMatch}/><路由组件={NoMatch}/></开关>
</路由器>)}}函数子({匹配}){//执行一些用户名检查if (match.params.username !== 'valid_username') {返回 (<div><重定向到="/404"/>
)}返回 (<div className="应用程序"><h3>ID:{match.params.username}</h3>
)}函数 NoMatch({ 位置 }) {返回 (<div><h3>404 - {location.pathname}
不匹配