我的应用程序看起来像:

class App extends Component {
  render() {
    <Router>
      <div>
      <Route exact path='/login' component={Login} />
      <Route exact path='/game' component={GameContainer} />
      <Route exact path='/chat' component={ChatContainer} />
      <Route exact path='/info' component={InfoContainer} />
    </div>
    </Router>  
  }

如果用户访问了/game下的页面,但没有登录,我想将他们重定向到登录

How to do it an elegant way in all routers?

推荐答案

见答案https://stackoverflow.com/a/43171515/208079.也许有比我更具代表性的人可以将其标记为复制品.

下面的示例中,idea组件需要使用Privater来包装身份验证.PrivateRoute将使用一些逻辑来确定用户是否经过身份验证,然后;允许呈现请求的路由,或重定向到登录页面.

此链接https://reacttraining.com/react-router/web/example/auth-workflow的react router培训文档中也描述了这一点.

以下是一个以上述为灵感的实现.

应用程序内.js(或路由发生的位置)

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import PrivateRoute from './PrivateRoute'
import MyComponent from '../src/MyComponent'
import MyLoginForm from '../src/MyLoginForm'

<Router>
  <Route path="/login" component={MyLoginForm} />
  <PrivateRoute path="/onlyAuthorizedAllowedHere/" component={MyComponent} />
</Router>

还有私密路由部分

// This is used to determine if a user is authenticated and
// if they are allowed to visit the page they navigated to.

// If they are: they proceed to the page
// If not: they are redirected to the login page.
import React from 'react'
import AuthService from './Services/AuthService'
import { Redirect, Route } from 'react-router-dom'

const PrivateRoute = ({ component: Component, ...rest }) => {

  // Add your own authentication on the below line.
  const isLoggedIn = AuthService.isLoggedIn()

  return (
    <Route
      {...rest}
      render={props =>
        isLoggedIn ? (
          <Component {...props} />
        ) : (
          <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
        )
      }
    />
  )
}

export default PrivateRoute

Reactjs相关问答推荐

如何实现黑暗模式 map ?

迁移到React Router Dom v6后,我是否错误地使用了Link组件?

使用useReducer时,props 未从父级传递给子或孙级

后端关闭时如何在REACTION AXIOS拦截器中模拟数据?

XChaCha20-Poly1305的解密函数

获取未捕获的错误:Gatsby生产版本上的最小化react 错误#418

当项目开始时,它不会从三元运算符(REACT)加载一些tailwind 类名称

react -无法获取函数的最新参数值

React,当我调用handleSubmit()函数时,我正在将application/json和multiform/data中的数据发送到后端,但student_image中没有数据:null

使用experial_useFormState将参数传递给服务器操作

数据表格组件需要所有行都具有唯一的ID属性.或者,您可以使用getRowId属性.

如何在 JS 中绘制具有不同笔画宽度的样条线

Formik onChange() 字段挂钩覆盖显示值和 Select 机制

React 测试库 - 如何断言异步函数之间的中间状态?

响应式媒体 React Tailwind

vdom 最终更新了 dom(在比较之后)任何 dom 更改实际上应该触发整个树的重绘和回流,那么 vdom 有什么用?

如何将值从下拉列表传递到 select 上的输入?响应式JS

运行开发服务器时如何为 Vite 指定运行时目录

如何在 React x 中返回组件?

为什么这两个 div 的渲染方式不同?