React onSubmit方法仅填充第二个事件

时间:2017-12-11 10:08:33

标签: javascript reactjs

我正在努力学习如何为表格,状态和道具工作。我创建了这个表单:

 render() {
        return (
            <div>
                <div className="container">
                    <form className="form-signin" onSubmit={this.loginClick.bind(this)}>
                        <control-label for="inputEmail" className="sr-only">Email address</control-label>
                        <input type="email" ref="username" id="inputEmail" className="form-control" placeholder="Email address" required autoFocus />
                        <control-label for="inputPassword" className="sr-only">Password</control-label>
                        <input type="password" ref="password" id="inputPassword" className="form-control" placeholder="Password" required />
                        <button className="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
                         </form>
                </div>
            </div>
        );
    }

提交方法:

 loginClick(event) {
        event.preventDefault();
        let un = this.refs.username.value;
        let pw = this.refs.password.value
        this.setState(
            {
                username: un,
                password: pw
            }
        );
        console.log(this.state);
    }

然而,我发现第一次点击,日志返回空的用户名和密码。当我第二次点击按钮时,用户名和密码是正确的。如果我然后修改用户名或密码,然后单击“提交”,则不做任何更改。显示旧的价值观。如果我第二次点击,则值会更新。

我做错了什么? (整个文件在这里:https://github.com/CraigInBrisbane/ReactLearning/blob/master/components/signinbox.jsx

1 个答案:

答案 0 :(得分:1)

setState操作是异步的,并且为了提高性能而进行批处理。这在setState

的文档中有解释

https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

因此,在您的示例中,状态尚未更新。您可以使用回调来检查更新后的状态:

loginClick(event) {
    event.preventDefault();
    let un = this.refs.username.value;
    let pw = this.refs.password.value
    this.setState({
            username: un,
            password: pw
        }, () => console.log(this.state)
    );
}

但这并不一定对你的情况有用。您只需打印出值

即可
loginClick(event) {
    event.preventDefault();
    let un = this.refs.username.value;
    let pw = this.refs.password.value
    this.setState({
            username: un,
            password: pw
    });
    console.log({
            username: un,
            password: pw
    });
}