【问题标题】:How to properly render a 404 page in React with React-Router?如何使用 React-Router 在 React 中正确渲染 404 页面?
【发布时间】:2017-08-15 13:56:32
【问题描述】:

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

有些网址是动态的,比如说,

www.site.com/user/(username)

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

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

【问题讨论】:

  • 不幸的是,唯一的方法是让组件中的条件匹配user/(username)。然后让组件呈现错误,或者您可以使用<Redirect ... /> 重定向到@canaan seaton 描述的错误页面

标签: reactjs react-router-v4


【解决方案1】:

使用切换然后重定向

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

https://reacttraining.com/react-router/web/api/Redirect

有效网址无重定向:/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

【讨论】:

  • 这实际上并没有告诉浏览器“httpcode 404”它告诉浏览器“200 ok”。当使用新文件(例如 chunk.js 文件)更新网站并且用户第一次访问该网站时,他们将获得不匹配页面作为 .js 内容。
【解决方案2】:

您可以检查this.props.match.username 是否存在。如果确实如此,则正常呈现,如果没有则使用React-Router Redirect 组件重定向到404 组件。如果您有多个需要此功能的路径,那么您可以考虑为此目的创建一个HOC

【讨论】:

    猜你喜欢
    • 2018-07-11
    • 2021-01-11
    • 1970-01-01
    • 2017-08-31
    • 2020-09-04
    • 2022-07-28
    • 2021-01-23
    • 1970-01-01
    相关资源
    最近更新 更多