如何使用 React-Router 在 React 中正确渲染 404 页面?

2023-12-20

我正在使用 React 和 React-Router 构建一个网站,我想在用户访问不存在的 url 时呈现 404 页面。

有些网址是动态的,例如,

www.site.com/user/(username)

如果具有特定用户名的用户不存在,如何使用react-router渲染404页面?在 API 调用期间,我是否必须在组件本身中手动编写代码来检查用户是否存在,然后将用户重定向到 404 组件?

我正在寻找将用户重定向到未找到页面的最佳方法。寻找如何做到最好的想法。


使用切换然后重定向

https://reacttraining.com/react-router/web/example/no-match https://reacttraining.com/react-router/web/example/no-match

https://reacttraining.com/react-router/web/api/Redirect 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'

class App extends Component {
  render() {
    return (
      <Router>
        <div>
          <Switch>
            <Route path="/user/:username" component={Child} />
            <Route path="/404" component={NoMatch} />
            <Route component={NoMatch} />
          </Switch>
        </div>
      </Router>
    )
  }
}

function Child({ match }) {
  // perform some username check
  if (match.params.username !== 'valid_username') {
    return (
      <div>
        <Redirect to="/404" />
      </div>
    )
  }
  return (
    <div className="App">
      <h3>ID: {match.params.username}</h3>
    </div>
  )
}

function NoMatch({ location }) {
  return (
    <div>
      <h3>
        404 - No match for <code>{location.pathname}</code>
      </h3>
    </div>
  )
}

export default App
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 React-Router 在 React 中正确渲染 404 页面? 的相关文章

随机推荐