React routing goes deep into actual user login

Keywords: Javascript React Attribute

This article is based on React routing for real user login function. It will involve new things such as form data binding, form submission and login judgment.

Continuation: In-depth Routing of React

First create a component - login form component

// file: src/components/UserLogin.js

'use strict';

import React from 'react';

export default class UserLogin extends React.Component {
    construct(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        };
    }
    
    render() {
        return <div>
            <h3>User login</h3>
            <div>
                <span>User name:</span>
                <span><input type="text"></span>
            </div>
            <div>
                <span>Password:</span>
                <span><input type="password"></span>
            </div>
            <div>
                <button>Sign in</button>
            </div>
        </div>
    }
}

Bind form elements to state, and bind click events to buttons

// file: src/components/UserLogin.js

'use strict';

import React from 'react';

export default class UserLogin extends React.Component {
    construct(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        };
    }
    
    setUserInfo(event, key) {
        // input form elements automatically bind an event object to an event function
        // The target attribute of the event object is equal to the input DOM element object, so event.target.value can get the value of the current input.
        let obj = {};
        obj[key] = event.target.value;
        // Update status
        this.setState(obj);
    }
    
    render() {
        return <div>
            <h3>User login</h3>
            <div>
                <span>User name:</span>
                <span><input type="text" onInput={(event) => {
                    this.setUserInfo(event, 'username');
                }}></span>
            </div>
            <div>
                <span>Password:</span>
                <span><input type="password" onInput={(event) => {
                    this.setUserInfo(event, 'password');
                }}></span>
            </div>
            <div>
                <button onClick={() => {
                    // User Name + Password Obtained by Test
                    alert(this.state.username + this.state.password);
                }}>Sign in</button>
            </div>
        </div>
    }
}

input form elements automatically bind an event object to an event function

The target attribute of the event object is equal to the input DOM element object, so event.target.value can get the value of the current input.

Define a user login operation class

This article does not involve background interface, temporarily simulate login with fixed username and password

// file: src/core/Passport.js

'use strict';

export default class Passport {
    constructor() {
        // User logon identity
        this.isLogin = false;
    }
    
    login(username, password, callback) {
        if (username === 'mi360' && password === '123') {
            // Successful login
            this.isLogin = true;
            // Handling the operation after successful login to the caller
            callback();
        } else {
            // Logon failure
            // Here's a simple pop-up message
            alert('Logon failed!');
        }
    }
}

Call the login operation class in the login form

// file: src/components/UserLogin.js

'use strict';

import React from 'react';

// Import login operation class
import Passport from '../core/Passport';

export default class UserLogin extends React.Component {
    construct(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        };
    }
    
    setUserInfo(event, key) {
        // input form elements automatically bind an event object to an event function
        // The target attribute of the event object is equal to the input DOM element object, so event.target.value can get the value of the current input.
        let obj = {};
        obj[key] = event.target.value;
        // Update status
        this.setState(obj);
    }
    
    render() {
        return <div>
            <h3>User login</h3>
            <div>
                <span>User name:</span>
                <span><input type="text" onInput={(event) => {
                    this.setUserInfo(event, 'username');
                }}></span>
            </div>
            <div>
                <span>Password:</span>
                <span><input type="password" onInput={(event) => {
                    this.setUserInfo(event, 'password');
                }}></span>
            </div>
            <div>
                <button onClick={() => {
                    // User Name + Password Obtained by Test
                    // alert(this.state.username + this.state.password);
                    
                    // Login operation
                    const p = new Passport();
                    p.login(this.state.username, this.state.password, () => {
                        // When the login is successful, jump the page
                        this.props.history.push('/news');
                    })
                    
                }}>Sign in</button>
            </div>
        </div>
    }
}

Add login component routing to our routing component

// file: src/components/MyRouter.js

'use strict';

import React from 'react';
import News from '../components/News';
import Shop from '../components/Shop';
import Detail from '../components/Detail';

// User login component
import Login from '../components/UserLogin';

import {
    HashRouter as Router,
    Route,
    Redirect,
    Link
} from 'react-router-dom';

export default class MyRouter extends React.Component {

    render() {
        return <Router>
            <div>
                <ul className="nav">
                    <li><Link to="/">home page</Link></li>
                    <li><Link to="/products">commodity</Link></li>
                    <li><Link to="/news">Journalism</Link></li>
                    <li><Link to="/login">User login</Link></li>
                </ul>

                <hr/>

                <Route exact path="/" component={Shop} />
                <Route exact path="/products" component={Shop} />
                <Route path="/products/:id" component={Detail} />
                <Route exact path="/news" component={News} />
                <Route path="/login" component={Login} />
            </div>
        </Router>
    }
}

Visit the page and preview the effect:

The correct user name and password in the input will jump to the news page!

Add login judgment

Add login judgment to the news page. If there is no login, automatically jump to the login page.

import React from 'react';
import News from '../components/News';
import Shop from '../components/Shop';
import Detail from '../components/Detail';
import Login from '../components/UserLogin';

import {
    HashRouter as Router,
    Route,
    Redirect,
    Link
} from 'react-router-dom';

// Import the user login operation class and instantiate it
import Passport from '../core/Passport';
let passport = new Passport();

export default class MyRouter extends React.Component {

    render() {
        return <Router>
            <div>
                <ul className="nav">
                    <li><Link to="/">home page</Link></li>
                    <li><Link to="/products">commodity</Link></li>
                    <li><Link to="/news">Journalism</Link></li>
                    <li><Link to="/login">User login</Link></li>
                </ul>

                <hr/>

                <Route exact path="/" component={Shop} />
                <Route exact path="/products" component={Shop} />
                <Route path="/products/:id" component={Detail} />
                // Using render attribute to define handler routing jump judgment
                <Route exact path="/news" render={(props) => {
                    if (passport.islogin) {
                        return <News {...props} />
                    } else {
                        return <Redirect to="/login" />
                    }
                }} />
                     // Pass the user action class instance to the user login component
                <Route path="/login" render={(props) => {
                    return <Login {...props} passport={passport} />
                }} />
            </div>
        </Router>
    }
}

Modify the user login operation class passed by the user login component using routing

'use strict';

import React from 'react';
import Passport from '../core/Passport';

export default class UserLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: ''
        }
    }

    setUserInfo(event, key) {
        let obj = {};
        obj[key] = event.target.value;
        this.setState(obj);
    }

    render() {
        return <div>
            <h3>User login</h3>
            <div>
                <span>User name:</span>
                <span><input type="text" onInput={(event) => {
                    this.setUserInfo(event, 'username');
                }} /></span>
            </div>
            <div>
                <span>Password:</span>
                <span><input type="password" onInput={(event) => {
                    this.setUserInfo(event, 'password')
                }} /></span>
            </div>
            <div>
                <button onClick={() => {
                    let p = this.props.passport == null ? new Passport() : this.props.passport;
                    p.login(this.state.username, this.state.password, () => {
                        // When the login is successful, jump the page
                        this.props.history.push('/news');
                    });
                }}>Sign in</button>
            </div>
        </div>
    }
}

Preview the access effect again, and test whether the news can be accessed without login, and whether it can be accessed after login!

Links to the original text: https://www.mi360.cn/articles...

Posted by thedream on Sun, 21 Jul 2019 22:07:20 -0700