javascript - this.setState 在我的 "validate(e)"方法中不起作用

标签 javascript reactjs authentication

在我的基本登录应用程序中,我将 isAuthorized 作为在构造函数中声明的 bool 状态。

当我的应用程序呈现表单的 onSubmit 部分并执行验证函数时,setState 不会将 this.state.isAuthorized 设置为声明的授权变量的值。这是为什么?我用谷歌到处搜索,但我不明白我做错了什么。

感谢您的宝贵时间

import React from 'react';
import '../css/bootstrap.css'; // You can download @ getbootstrap.com
import '../css/main.css'; // located in the bottom as a comment

class Login extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            users: [
                {
                    "id":1,
                    "first":"John",
                    "last":"Doe",
                    "email":"johnee23@email.com"
                },
                {
                    "id":2,
                    "first":"Alexander",
                    "last":"Richards",
                    "email":"alexthegreat44@email.com"
                },
                {
                    "id":3,
                    "first":"Raymond",
                    "last":"Jefferson",
                    "email":"rayray007@email.com"
                }
            ],
            credentials: [
                {
                    "id":1,
                    "username":"johnee23",
                    "password":"abc123"
                },
                {
                    "id":2,
                    "username":"alexthegreat44",
                    "password":"alexandra"
                },
                {
                    "id":3,
                    "username":"rayray007",
                    "password":"agentray"
                }
            ],
            isAuthorized: false
        };
        this.validate = this.validate.bind(this);
    }

    validate(e) {
        const username = e.target.querySelector('input[type="text"]').value;
        const password = e.target.querySelector('input[type="password"]').value;
        let authorized = false;
        {this.state.credentials.map(credential => {
            if(username === credential.username && password === credential.password) {
                authorized = true;
            }
            //alert(`Going through\nusername: ${credential.username}\npassword: ${credential.password}\nauthorized?: ${this.state.auth}\n\nYour input:\nusername: ${username}\npassword: ${password}`);
            alert(`${credential.username} === ${username}: ${credential.username === username}\n${credential.password} === ${password}: ${credential.password === password}\n${credential.username} === ${username} && ${credential.password} === ${password}: ${credential.username === username && credential.password === password}\nauthorized: ${authorized}`)
        })}
        alert(`authorized after done: ${authorized}`);


        // this.state.isAuthorized is not setting to true, even though the
        // authorized variable is already true. Confirmed through alert popups
        this.setState({
            isAuthorized: authorized,
        });
        // ---------------------------------------------------------------------

        alert(`username: ${username}\npassword: ${password}\n\nisAuthorized: ${this.state.isAuthorized}\nauthorized: ${authorized}`);
    }

    render() {
        return (
            <div>
                <header>
                    <nav class="navbar navbar-expand navbar-dark bg-dark fixed-top">
                        <a href="#"><h2 class="navbar-brand">My Login Application</h2></a>
                        <div class="collapse navbar-collapse">
                            <div class="navbar-nav right">
                                <a href="#" className="nav-item nav-link">Home</a>
                                <a href="#" className="nav-item nav-link">Sign In</a>
                            </div>
                        </div>
                    </nav>
                </header>
                <br /><br /><br /><br /><br /><br /><br />
                <div className="container">
                    <div className="row">
                        <div className="col-md-8">

                            // ----- This is the form that submits on the validate function above ----------

                            <form action="#" onSubmit={this.validate}>
                                <h1>Sign In</h1>
                                <br />
                                <div class="form-group">
                                    <label for="username">Your Username</label>
                                    <input type="text" className="form-control" id="username" placeholder="Enter Username" />
                                </div>
                                <div class="form-group">
                                    <label for="password">Your Password</label>
                                    <input type="password" className="form-control" id="password" placeholder="Enter Password" />
                                </div>
                                <br />
                                <button type="submit" className="btn btn-primary" onClick={this.validate}>Enter</button>
                            </form>

                            // -----------------------------------------------------------------------------

                        </div>
                        <div class="col-md-4 text-right vl  ">
                            <br />
                            <h1>Don't have an account?</h1>
                            <br />
                            <a href="#" className="btn btn-success" role="button">Sign up here!</a>
                        </div>
                    </div>
                    <br /><br /><br /><br /><br /><br /><br /><br /><br />
                </div>

                <div className="container">
                    <div className="row">
                        <div className="col-md-4"></div>

                        <div className="col-md-6">

                            <br /><br />
                            <h1>Users</h1>
                            <ul>
                                {this.state.users.map(user =>
                                    <div>
                                        <li key={user.id}>Name: {user.first} {user.last}</li>
                                        <li key={user.id}>Email: {user.email}</li>
                                        <br />
                                    </div>
                                )}
                            </ul>
                            <br /><br />
                            <h1>Credentials</h1>
                            <ul>
                                {this.state.credentials.map(cred =>
                                    <li key={cred.id}>{cred.username}: {cred.password}</li>
                                )}
                            </ul>
                            <br /><br />

                        </div>

                        <div className="col-md-2"></div>
                    </div>
                </div>

                <footer>
                    <nav class="navbar navbar-light bg-light sticky-bottom">© Lockerroom Buzz: 2019-2020</nav>
                </footer>
            </div>
        );
    }
};

// Main.css
// ---------
// .right {
//   padding-left: 900px;
// }
//
// .title {
//   padding-left: 0px;
// }
//
// .vr {
//   border-right: 1px solid;
// }
//
// .navbar {
//   background-color: purple;
//   width: 100%;
// }
//
// .jumbotron {
//   width: 100%;
// }
//
// .center {
//   text-align: center;
//   margin-left: 25px;
// }
//
// .centralize {
//   padding-right: 20px;
// }
//
// .people {
//   width: 18rem;
// }
//
// .red {
//   color: red;
// }


export default Login;

最佳答案

setState 不是同步的,这就是原因:

this.setState({ isAuthorized: authorized });
console.log(this.state.isAuthorized) // here logs the value prior of the setState

如果您想在 setState 之后立即记录,请传递回调作为第二个参数:

this.setState({ isAuthorized: authorized }, () => console.log(this.state.isAuthorized));

关于javascript - this.setState 在我的 "validate(e)"方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54216832/

相关文章:

javascript - 从 Internet Explorer 错误对象中检索行号

javascript - Assetic javascripts 从非空源(包内)创建空文件

javascript - 导出默认不工作 webpack,reactjs

javascript - React-router 4 滚动恢复可防止 anchor 链接的 native 行为

authentication - 为什么 Google Cloud Translate 上的持久 503 服务不可用?

javascript - 一段时间后关闭Bootstrap Modal

JavaScript 监听器不断增加

javascript - React 如何区分用于求值的大括号和用作 JS 的大括号?

java - 我应该如何在 Java 的应用程序层之间传递主题/主体/角色?

javascript - firebase.auth().onAuthStateChanged 不工作