首页 > 解决方案 > 无法在 react.js 中访问功能组件变量作为回报

问题描述

我想通过访问它来显示在 useState 中声明的错误变量,但它会抛出错误"TypeError: Cannot read property 'error' of undefined".

这是我到目前为止所尝试的。

    Const Login = () => {
    let history = useHistory();

    const [form,setForm] = useState({
        email:'',
        password:'',
        error:''
    })

    const handleSubmit = async(e)=>{
        e.preventDefault();
        let a = await login(form);
        console.log(a);
        if(typeof a !== "undefined") {
            history.push('/Trial')
        }
        else {
             this.state.error = "Invalid Email or Password";
        }
        console.log('Logged in')
        console.log(e);
    }

    return (
        <div>
            <head>
                <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
                <title>Sign In</title>
                <link rel="stylesheet" href="login.css"></link>
            </head>
                <body>
                    <div className="container1 bg">
                        <div className="forms-container">
                            <div className="signin">
                                <form className="sign-in-form" onSubmit={handleSubmit}>
                                    <h2 className="title">Sign In</h2>
                                    <div className="input-field">
                                        <i className="fas fa-envelope"></i>
                                        <input type="email" placeholder="Email Address" onChange={(e) => setForm({...form, email: e.target.value})}/>
                                    </div>
                                    <div className="input-field">
                                        <i className="fas fa-lock"></i>
                                        <input type="password" placeholder="Password" onChange={(e) =>setForm({...form, password: e.target.value})}/>
                                    </div>
                                    <button class="btn1 solid">Login</button>
                                    <p class="social-text" style={"color: red"}>{this.error}</p>
                                </form>
                            </div>
                        </div>
)

标签: reactjsreact-hooksreact-functional-component

解决方案


推荐阅读