登录时重定向-React.js [英] Redirect on Login - React.js

查看:33
本文介绍了登录时重定向-React.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的用户成功登录(在Login.js内)后使用React Router进行简单的重定向,并阻止用户重新访问登录页面(在index.js内).

I am trying to do a simple Redirect with React Router after my user successfully logs in (inside Login.js), and prevent the user from revisiting the login page (inside index.js).

在Login.js中,我在登录按钮标记中具有 onSubmit = {this.handleSubmit} ,并且具有 handleSubmit(e)函数来进行重定向.我已经在线尝试了其他一些解决方案,但是我认为我对< Redirect/> 组件的用法的理解是错误的.

In Login.js, I have onSubmit={this.handleSubmit} within the login button tag, and handleSubmit(e) function to Redirect. I have tried a few other solutions online, but I think my understanding on the usage of the <Redirect/> component is wrong.

在index.js中,我有一个条件来测试用户是否已登录,并(较差)警告用户为什么他们无法访问所需页面.我在YouTube视频中看到了这一点,但不确定这是否是获得理想效果的最佳方法.

In index.js, I have a conditional that tests if the user is signed in, or not signed in, and (poorly) alerts the user on why they can't visit the desired page. I saw this in a Youtube video, but not sure if it's the best way to get the desired effect.

当前,当我成功登录时,警报如果您登录后将无法登录!,但是我显然不希望警报成功后立即关闭登录时,我希望重定向首先触发.如果在圆括号中交换两者,React会引发错误.

Currently, when I log in successfully, the alert You can't login if you are logged in! is set off, but I obviously don't want the alert going off right after a successful login, I want the Redirect to trigger first. If I swap the two in the parenthesis, React throws an error.

如何成功登录后立即触发重定向,但不发送警报如果您登录则无法登录!?

How do I get the Redirect to trigger right after a successful login, but not send the alert You can't login if you are logged in!?

Login.js组件:

import React, { Component } from 'react';
import fire from '../config/Fire.js';
import { Link, Redirect } from 'react-router-dom';
import PasswordMask from 'react-password-mask';

export default class Login extends Component {
    constructor(props) {
        super(props);
        this.login = this.login.bind(this);
        this.handleChange = this.handleChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.signup = this.signup.bind(this);
        this.state = {
          email: '',
          password: ''
        };
      }

    handleChange(e) {
        this.setState({ [e.target.name]: e.target.value });
    }

    handleSubmit(e) {
        e.preventDefault();
        <Redirect to="/ticket-list"/>;
    }

    login(e) {
        e.preventDefault();
        fire.auth().signInWithEmailAndPassword(this.state.email, this.state.password).catch((error) => {
            alert(error);
            });
    }

    signup(e){
        e.preventDefault();
        fire.auth().createUserWithEmailAndPassword(this.state.email, this.state.password).catch((error) => {
            alert(error);
            })
    }

    render() {
        return (
        <div className="m-container">
            <h1>Login</h1>
            <hr/>
            <div className="m-container">
                <form onSubmit={this.submitForm}>
                <div>
                    <label for="exampleInputEmail1">Email address: </label>
                    <br/>
                    <input 
                    value={this.state.email} 
                    onChange={this.handleChange} 
                    type="text" 
                    name="email" 
                    id="exampleInputEmail1" 
                    placeholder="you@email.com" />
                </div>
                <div>
                    <label for="exampleInputPassword1">Password: </label>
                    <br/>
                    {/* Margin issue when showing and hiding password */}
                    <PasswordMask 
                    value={this.state.password} 
                    onChange={this.handleChange} 
                    type="password" 
                    name="password" 
                    id="exampleInputPassword1" 
                    placeholder="**********"
                     />
                </div>
                <br/>
                <button 
                    type="submit" 
                    className="button" 
                    onClick={this.login}
                    onSubmit={this.handleSubmit}>Login</button>
                &nbsp;
                <Link className="button-inv" to="/register">Register</Link>
                </form>
            </div>
        </div>
        );
    }
}

index.js组件:

import React, { Component } from 'react';
import { Route, Switch, Redirect } from 'react-router-dom';

import Home from './Home';
import Technician from './Technician';
import About from './About';
import Register from './Register';
import Login from './Login';
import TicketList from './TicketList';

export default class Routes extends Component {

    render() {
        return (
        <Switch>
            <Route path="/" exact component={Home} />
            <Route path="/technician" exact component={Technician} />
            <Route path="/about" exact component={About} />
            <Route path="/register" exact render={()=>(
                this.props.user ? (alert("You can't register if you are logged in!"), (<Redirect to="/"/>)) : (<Register/>)
            )} />
            <Route path="/login" exact render={()=>(
                this.props.user ? (alert("You can't login if you are logged in!"), (<Redirect to="/ticket-list"/>)) : (<Login/>)
            )} />
            <Route path="/ticket-list" exact render={()=>(
                this.props.user ? (<TicketList/>) : (alert("You must log in to visit this page."), (<Redirect to="/login"/>))
            )} />
        </Switch>
        );
    }
};

App.js :

import React, { Component } from 'react';
import { BrowserRouter } from 'react-router-dom';
import Routes from './routes';
import fire from './config/Fire.js';

// CSS
import './assets/css/App.css';
import './assets/css/Header.css';
import './assets/css/Footer.css';
// Components
import Header from './components/Header';
import Footer from './components/Footer';

class App extends Component {
  constructor(props){
    super(props);
    this.state = {
      user:{},
    }
  }

  //When component is done rendering for the first time
  componentDidMount(){
    this.authListener();
  }

  // If user logs in (if) or out (else) this is called
  authListener() {
    fire.auth().onAuthStateChanged((user) => {
      //console.log(user);
      if (user) {
        this.setState({ user });
      } else {
        this.setState({ user: null });
      }
    });
  }


  render() {
    return (
      <BrowserRouter>
        <div className="wrapper">
          <Header user={this.state.user} />
          <div className="body">
            <Routes user={this.state.user} />
          </div>
          <Footer />
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

推荐答案

要解决您的问题,您必须为登录/注册创建单独的组件,并进行警报和重定向取决于用户.您将需要来自 react-router lib中的名为 withRouter 的高阶组件.

To solve your problem you have to create separate components for Login/Register and make alerts and redirects there depends on user. You will need High Order Component named withRouter from react-router lib.

登录容器:

class LoginContainer extends Component {
  constructor(props) {
    super(props)

    if (props.user) {
      alert("You can't login if you are logged in!")
      props.history.push('/ticket-list')
    }
  }

  render() {
    return <Login />;
  }
}

export default withRouter(LoginContainer)

然后像下面这样在您的 Routes 中使用它:

And then use it in your Routes like this:

<Route path="/login" render={()=> <LoginContainer user={this.props.user} />} />

用于 Register 的同一个,或者您可以制作一个并获取 alertMessage redirectTo 之类的参数,并使用它们代替硬编码值.

The same one for Register or you can just make one and get params like alertMessage and redirectTo and use them instead of hardcoded values.

此外,我建议您将auth HoC用于您的私有路由,未经身份验证便无法访问.

In addition, I advice you to use auth HoC for your private routes, which is not accessible without authentication.

我更喜欢使用新的上下文API来共享诸如用户,本地化等实体,因此这里是一个示例,该示例说明如何使用React Context API制作 PrivateRoute

I'd prefer to use new context API for sharing such entity as user, localization, etc, so here is an example how to make PrivateRoute using React Context API.

App.js

...
export const UserContext = React.createContext();
...
class App extends Component {

    state = {
        user: null
    }

    componentDidMount() {
      this.authListener();
    }

    authListener() {
      fire.auth().onAuthStateChanged(user => {
        if (user) {
          this.setState({ user });
        }
      });
    }

    render() {
       <UserContext.Provider value={this.state}>
           <BrowserRouter>
               // another things Switch etc
               ...
           </BrowserRouter>
       </UserContext.Provider>
    }
}

PrivateRoute.jsx

import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom'
import { UserContext } from './App'

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

  class Authentication extends Component {

    handleRender = props => {
      if (!this.props.user) {
        return <Redirect to="/login" />
      } else {
        return <ComposedComponent user={this.props.user} {...props} />
      }
    }

    render() {
      return (
        <Route {...rest} render={this.handleRender} />
      );
    }
  }

  return (
    <UserContext.Consumer>
      {
        ({ user }) => <Authentication user={user} />
      }
    </UserContext.Consumer>
  )
};

export default PrivateRoute

然后,如果您不想显示未经身份验证的页面,则可以使用 PrivateRoute 而不是 Route .

And then you can use PrivateRoute instead of Route in case when you don't want to show page without authentication.

import PrivateRoute from './PrivateRoute'

...

// all of the component code
render() {
    ...
    <Switch>
        <PrivateRoute path="/ticket-list" component={<TicketList />} />
    </Switch>
    ...
}

希望有帮助!祝你好运!

Hope it helps! Good luck!

这篇关于登录时重定向-React.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆