我正在努力学习如何为表格,状态和道具工作。我创建了这个表单:
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)
答案 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
});
}