我有这个Ant Design表单,目前,我一直坚持输出错误消息:在下面所附的代码块中,handleSubmit
没有响应。提交错误的输入后,我想立即看到错误消息“用户名和密码不匹配”,但该消息仅在其中一个字段更改后才显示(我有多个更改,但我只提出来使内容保持清晰)
为您提供信息,我提交了错误的数据后就立即记录了“更新道具”,但错误消息仅在对另一个字段进行了其他更改之后才更改。
class NormalLoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {username: '', usernameProps: {},};
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event => event.preventDefault();
postData('/account/login', this.state)
.then(data => {
if (data.success) {window.location = '/';}
else {
this.usernameProps = {
hasFeedback: true, validateStatus: "error",
help: "Username and Password do not match"
}
console.log('updating props'); // Here is the log
}
});
}
render () {
return (
<Form
style={{ width: "100%" }} onFinish={this.handleSubmit}
noValidate
>
<Form.Item name="username" {...this.usernameProps}
onChange={this.handleUsernameChange}>
<Input placeholder="Username"/>
</Form.Item>
<Form.Item>
<Button type="submit" htmlType="submit" style={{ width: "100%" }}>
Log in
</Button>
</Form.Item>
</Form>
)
}
};
ReactDOM.render(<NormalLoginForm />, document.getElementById("root"));
有人可以告诉我我在哪里做错了吗?预先非常感谢。
答案 0 :(得分:1)
在更新状态时,请使用setState方法,并避免像在此处那样直接更新状态。
this.usernameProps = {
hasFeedback: true, validateStatus: "error",
help: "Username and Password do not match"
}
执行此操作:
const userNameState = {...this.state.usernameProps, hasFeedback: true, validateStatus: "error",
help: "Username and Password do not match"};
this.setState({usernameProps: userNameState});
您可以以this.state.usernameProps
的形式使用此状态