在 React onSubmit 中更新道具

Updating Props in React onSubmit

我有这个 Ant Design 表单,目前,我一直在输出错误消息:在下面附加的代码块中,handleSubmit 没有响应。我想在提交错误输入后立即看到错误消息“用户名和密码不匹配”,但该消息仅在其中一个字段更改后显示(我有多个,但我只是为了保持清晰而提出这个) .

供您参考,我一提交错误数据就记录了“updating props”,但错误消息仅在对另一个字段进行额外更改后才会更改。

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")); 

谁能告诉我我哪里做错了?非常感谢。

更新状态时使用 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