首页 > 解决方案 > 尽管 Semantic-React-UI 表单中存在错误状态,但成功消息仍会继续触发

问题描述

我正在尝试根据表单组件的状态触发适当的消息,以在表单提交时进行前端验证。

我正在进行的主要验证之一是检查电子邮件是否存在,如果存在,则应该继续看到错误消息触发。如果数据库中不存在成功消息,则应触发;当然,如果其他验证通过!

我正在使用Semantic-UI React Forms来帮助验证。

这些是我在表单组件的状态对象上设置的键和值:

this.state = {
  fadeUp: 'fade up',
  duration: 500,
  username: '',
  password: '',
  usernameError: false,
  passwordError: false,
  formSuccess: false,
  formError: false,
  userNameDup: false,
}

这是我的提交处理程序,它在提交时触发:

handleSubmit(event) {
 event.preventDefault();
 var error = false

 var { username, password, userNameDup } = this.state

 var mailFormat = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/


if (!username.match(mailFormat)) {
  this.setState({ usernameError: true });
  error = true;
} else {
  this.setState({ usernameError: false });
}

if (password.length < 8) {
  this.setState({ passwordError: true });
  error = true;
} else {
  this.setState({ passwordError: false })
}

if (error) {
  this.setState({ formSuccess: false });
  return;
} else {
  this.setState({ formSuccess: true });
}

window.fetch('http://localhost:8016/users/registration', {
  method: 'POST',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  body: JSON.stringify({ username_email: username, password: password })
})
  .then(this.handleErrors)
  .then(function (response) {
    console.log(`response ${response}`)
    return response.json()
  }).then(function (data) {

    console.log('User created:', data)
  }).catch(function (error) {
    console.log(error);
  });

   setTimeout(() => { this.setState({ username: '', password: '' }) })

 }

handleErrors(response) {
  if (!response.ok) {
    if (response.status === 409) {
      console.log("response.status ", response.status);
      this.setState({
      userNameDup: true, formError: true, formSuccess:false
    });
    return;
  }
 } else {
  this.setState({
    userNameDup: false, formError:false
  })
 }
   return response;
 }

这是表单视图/标记的一部分:

  {console.log("formSuccess 1", formSuccess)}

<Form size='large'
  onSubmit={this.handleSubmit}
  error={userNameDup || formError}>
  {console.log("formSuccess 2", formSuccess)}

  <Segment stacked>
    <Form.Input fluid icon='user'
      iconPosition='left'
      placeholder='E-mail address, e.g. joe@schmoe.com'
      name='username'
      value={username}
      onBlur={this.handleBlur}
      onChange={this.handleChange}
      error={usernameError}
    />

    <Transition visible={usernameError}
      animation='scale'
      duration={duration}>
      <Message error content='username_Email is in incorrect format e.g. joe@schmoe.com' />
    </Transition>

    <Form.Input fluid icon='lock'
      iconPosition='left'
      placeholder='Password'
      name='password'
      value={password}
      onBlur={this.handleBlur}
      onChange={this.handleChange}
      error={passwordError}
    />

    <Transition visible={passwordError}
      animation='scale'
      duration={duration}>
      <Message error content='Password needs to be greater than eight characters.' />
    </Transition>

    <Button color='teal'
      fluid size='large'
      disabled={!username || !password}>
      Register
      {/* {isLoggedIn ? `Register` : `Log-in`} */}
    </Button>

    <Transition visible={userNameDup || formError}
      unmountOnHide={true}
      animation='scale'
      duration={duration}>
      <Message
        error
        centered="true" header='This email exists.'
        content='Please re-enter another email address.' />
    </Transition>

    <Transition visible={formSuccess}
      unmountOnHide={true}
      animation='scale'
      duration={duration}>
      <Message
        success
        header='Your user registration was successful.'
        content='You may now log-in with the username you have chosen.' />
    </Transition>
  </Segment>
</Form>

我提供了一个gif,您可以看到导致问题的formSuccess关键跳转到一秒钟。true但我认为我handleError在提交时会处理这个问题?

再次处理错误:

 handleErrors(response) {
    if (!response.ok) {
      if (response.status === 409) {
        console.log("response.status ", response.status);
        this.setState({
          userNameDup: true, formError: true, formSuccess:false /* why doesn't it stay falsey? */
        });
        return;
      }
    } else {
      this.setState({
        userNameDup: false, formError:false
      })
    }
    return response;
  }

句柄提交的摘录:

window.fetch('http://localhost:8016/users/registration', {
  method: 'POST',
  headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },
  body: JSON.stringify({ username_email: username, password: password })
})
  .then(this.handleErrors) /* Shouldn't this be where it changes to false? */
  .then(function (response) {
    console.log(`response ${response}`)
    return response.json()
  }).then(function (data) {

    console.log('User created:', data)
  }).catch(function (error) {
    console.log(error);
  });

每次点击注册时,消息不应该动画吗?

请帮忙!!!谢谢!

标签: javascriptreactjsfetch-apisemantic-ui-reactreact-state

解决方案


if (error) {
    this.setState({ formSuccess: false });
    return;
} else {
    this.setState({ formSuccess: true });
}

当您点击提交时,error变量的初始值为 false,因此它会将formSuccess状态更改为 true,直到 promise 被解决 - 当handleErrors被调用并将其更改回 false。您应该只formSuccess在从 db 获取数据后设置为 true,即在.then()块内部以避免异步问题。

解决它的一种方法是在您获取数据并验证用户是新用户后显示成功消息,如下所示:

handleErrors(response) {
  if (!response.ok) {
    if (response.status === 409) {
      console.log("response.status ", response.status);
      this.setState({
      userNameDup: true, formError: true, formSuccess:false
    });
    return;
  }
 } else {
  this.setState({
    userNameDup: false, formError:false, formSuccess: true
  })
 }
   return response;
 }

然后您的前端验证仅限于显示错误消息。

if (!username.match(mailFormat)) {
  this.setState({ usernameError: true, formSuccess: false } });
} else {
  this.setState({ usernameError: false });
}

if (password.length < 8) {
  this.setState({ passwordError: true, formSuccess: false } });
} else {
  this.setState({ passwordError: false })
}

推荐阅读