【问题标题】:Updating Props in React onSubmit在 React onSubmit 中更新 Props
【发布时间】:2020-11-07 23:43:09
【问题描述】:

我有这个 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")); 

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

【问题讨论】:

    标签: reactjs forms submit react-props


    【解决方案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的形式中使用这个状态

    【讨论】:

    • 在表单中将 usernameProps 作为 this.state.usernameProps 传递
    猜你喜欢
    • 2015-12-01
    • 2021-10-09
    • 2020-08-10
    • 1970-01-01
    • 2015-08-24
    • 2017-10-20
    • 2016-12-30
    • 2021-12-05
    • 2019-09-11
    相关资源
    最近更新 更多