Reactjs 中的简单条件路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48497510/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:24:25  来源:igfitidea点击:

Simple Conditional Routing in Reactjs

reactjsreact-routerreact-reduxreact-router-v4react-router-dom

提问by Srikanth Gowda

How to make conditional Routing, if and only if some conditions satisfies then only routing should happen. for example, if and only if the user enters the correct credentials login should be successful and the user should be able to see the welcome page.

如何进行条件路由,当且仅当某些条件满足时才应该进行路由。例如,当且仅当用户输入正确的凭据时登录才应该成功并且用户应该能够看到欢迎页面。

if we hit directly some URL like 'localhost:8080/welcome' that should not be navigated to welcome page, only after login welcome page should be seen. how can I achieve this, can anyone help me please..thank you.

如果我们直接点击一些像“localhost:8080/welcome”这样不应该导航到欢迎页面的 URL,只有在登录后才能看到欢迎页面。我怎么能做到这一点,有人可以帮我吗...谢谢。

App.js

应用程序.js

import React, { Component } from 'react';
import Header from './Header';

class App extends Component{
  render(){
   return(
     <div>
       <Header />
     </div>
   );
  }
}
export default App;

Header.js

头文件.js

import React, { Component } from 'react';
import {Link} from 'react-router-dom';
import Login from './Login';
import SignUp from './SignUp';

class Header extends Component{
render(){
  return(
    <div>
    <nav class="navbar navbar-default">
     <div class="container-fluid">
     <ul class="nav navbar-nav">
      <li><Link to={Login}>Login</Link></li>
      <li><Link to={Login}>SignUp</Link></li>
    </ul>
    </div>
    </nav>

    </div>
   );
 } 
}

export default Header;

AllRoutes.js

AllRoutes.js

import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Login from './Login';
import SignUp from './SignUp';
import Welcome from './Welcome';

class AllRoutes extends Component{
 render(){
   return(
     <Switch> 
       <Route exact path="/login" component={Login} />
       <Route exact path="/signup" component={SignUp} />
       <Route exact path="/Welcome" component={Welcome} />
     </Switch>
   );
  }
 }
 export default AllRoutes;

Welcome.js

欢迎.js

import React, { Component } from 'react'; 

class Welcome extends Component{
render(){
 return(
  <div>
   <h2>Welcome to MainPage..</h2>
  </div>
  );
 }
}
export default Welcome;

回答by jerelmiller

To help answer your question, I think you may need to also ask howthat route should get blocked. Looking through the example above, you don't yet have a mechanism that helps answer the question of "should I be able to visit this page". That might come from state, redux, or some other means of determining if the user is logged in.

为了帮助回答您的问题,我认为您可能还需要询问应该如何阻止该路线。查看上面的示例,您还没有一种机制可以帮助回答“我是否应该能够访问此页面”的问题。这可能来自state、redux 或其他确定用户是否已登录的方法。

Since react-routeris just plain React (one of my favorite parts!!) you have all the tools available to you that you would to conditionally show anypart of your React app.

由于react-router只是简单的 React(我最喜欢的部分之一!!),您拥有所有可用的工具,您可以有条件地显示React 应用程序的任何部分。

Here are a couple examples of how you might achieve this (by no means is this exhaustive. Be creative! It all depends on your requirements and the tools you are using)

以下是您如何实现这一目标的几个示例(绝不是详尽无遗的。要有创意!这一切都取决于您的要求和您使用的工具)

class AllRoutes extends Component{
  render(){
    return(
      <Switch> 
        <Route exact path="/login" component={Login} />
        <Route exact path="/signup" component={SignUp} />
        { this.state.authenticated && 
          <Route exact path="/Welcome" component={Welcome} />
        }
      </Switch>
    );
  }
}

One of my favorite ways to accomplish this is creating a ProtectedRoutecomponent

我最喜欢的方法之一是创建一个ProtectedRoute组件

class ProtectedRoute extends Component {
  render() {
    const { component: Component, ...props } = this.props

    return (
      <Route 
        {...props} 
        render={props => (
          this.state.authenticated ?
            <Component {...props} /> :
            <Redirect to='/login' />
        )} 
      />
    )
  }
}

class AllRoutes extends Component {
  render() {
    return (
      <Switch>
        <Route path='/login' component={Login} />
        <ProtectedRoute path='/welcome' component={Welcome} />
      </Switch>
    )
  }
}

While I didn't include any specific logic to how state.authenticatedwas set, this may come from anywhere (by no means does it needs to come from state). Do your best to answer the question of "how do I determine whether a user is authenticated" and use that mechanism as the means to handle route authentication.

虽然我没有包含任何关于如何state.authenticated设置的特定逻辑,但这可能来自任何地方(绝不需要来自state)。尽力回答“我如何确定用户是否通过身份验证”的问题,并使用该机制作为处理路由身份验证的手段。

回答by Mayank Shukla

For that you need to break the entire app into two parts, normally accessible and protected part. Protected part will be accessible only after successful login.

为此,您需要将整个应用程序分为两部分,通常可访问的部分和受保护的部分。只有成功登录后才能访问受保护的部分。

To achieve that functionality, create a wrapper of protected part, and define its routes with path='/', and put the condition inside that. All the protected routes should be defined inside that wrapper component. If anyone try to access those routes without login, wrapper will redirect them to login page.

要实现该功能,请创建受保护部分的包装器,并使用 定义其路由path='/',并将条件放入其中。所有受保护的路由都应该在该包装器组件内定义。如果有人试图在没有登录的情况下访问这些路由,包装器会将他们重定向到登录页面。

Like this:

像这样:

class AllRoutes extends Component{
 render(){
   return(
     <Switch> 
       <Route exact path="/login" component={Login} />
       <Route exact path="/signup" component={SignUp} />
       <Route path="/" component={AppWrapper} />
     </Switch>
   );
  }
 }

AppWrapperComponent (assuming you are using some way to maintain whether user is logged-in or not, so put the proper check in if condition):

AppWrapper组件(假设您正在使用某种方式来维护用户是否已登录,因此请正确检查 if 条件):

import { Redirect } from 'react-router-dom'

class AppWrapper extends Component{
  render(){

  if(/*not login*/)
    return <Redirect to="/login" />

   return(
     <div>
       App wrapper
       <Route path='/Welcome' component={Welcome} />
     </div>
   );
  }
}

回答by Shrey Kejriwal

Best way is to create a HOC. Considering you are maintaining auth state in your redux store. Or else you can check with your own variable.

最好的方法是创建一个 HOC。考虑到您正在 Redux 存储中维护身份验证状态。否则,您可以检查自己的变量。

Create requireAuth.js

创建 requireAuth.js

import React, { Component } from 'react';
import { connect } from 'react-redux';

export default function(ComposedComponent) {
  class Authentication extends Component {
    static contextTypes = {
      router: React.PropTypes.object
    }

    componentWillMount() {
      if (!this.props.authenticated) {
        this.context.router.push('/');
      }
    }

    componentWillUpdate(nextProps) {
      if (!nextProps.authenticated) {
        this.context.router.push('/');
      }
    }

    render() {
      return <ComposedComponent {...this.props} />
    }
  }

  function mapStateToProps(state) {
    return { authenticated: state.auth.authenticated };
  }

  return connect(mapStateToProps)(Authentication);
}

Now in the routes you can use this hoc and pass the component.

现在在路由中你可以使用这个 hoc 并传递组件。

import RequireAuth from './requireAuth';
...

<Route exact path="/Welcome" component={RequireAuth(Welcome)} />

回答by learner

You can do something like:

您可以执行以下操作:

 let redirectToUrl;
      if ( not logged in ) //check condition
      {
        redirectToUrl = <Redirect to={loginPage}/>;
      }

and use the same:

并使用相同的:

  <Router>
     <div>
      {redirectToUrl}
       <Switch>
       <Route />
        </switch>
       </div>
</Router>

For the same you need to import from react-router-dom:

同样,您需要从 react-router-dom 导入:

import {
  BrowserRouter as Router,
  Route,
  browserHistory,
  Redirect,
  Link,
  Switch
} from "react-router-dom";

回答by Rishikesh Dhokare

You can use Redirectfrom react-router-dom.

您可以使用Redirectreact-router-dom.

Here is a good example - https://scotch.io/courses/using-react-router-4/authentication-with-redirect

这是一个很好的例子 - https://scotch.io/courses/using-react-router-4/authentication-with-redirect

回答by nagarjuna

The best and simple thing you can do is to create a state variable login and route based on the boolean values. the logic to set is up to you. i can show an example of simple routing based on condition. I store my pages in a array and use the map function to switch to different routes. For an example I have inserted my DesignerHome.js for your reference

您可以做的最好和最简单的事情是基于布尔值创建状态变量登录和路由。要设置的逻辑取决于您。我可以展示一个基于条件的简单路由的例子。我将我的页面存储在一个数组中,并使用 map 函数切换到不同的路线。例如,我插入了我的 DesignerHome.js 供您参考



This is my App.js

这是我的 App.js

import React,{Component} from 'react';
import{BrowserRouter as Router,Switch,Route,Redirect,}   from 'react-router-dom'
import MainHome from './MainHome'
import DesignerHome from './designer/DesignerHome'

export default class App extends Component{
  constructor(){
    super()
    this.state={
      login : true,
      r_page :[
        {
          path :'/designerhome',
          component : DesignerHome,
        },]
      }    
    } 
  render(){  
    return(      
      <Router>
        <Switch >  
          <Route path='/' exact component={MainHome}/>            
          {this.state.r_page.map((item , i)=>(this.state.login?
<Route exact {...item}/> :  <Redirect to="/" /> ))}
        </Switch>        
      </Router> 

    )    
  }
}




This is my DesignerHome.js

这是我的 DesignerHome.js

import React,{Component} from 'react';

export default class DesignerHome extends Component{
  render(){
    return(
        <div>
            designer home
        </div>
    )
  }
}