javascript - 尽管 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>
我提供了一个,您可以看到导致问题的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);
});
每次点击注册时,消息不应该动画吗?
请帮忙!!!谢谢!
解决方案
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 })
}
推荐阅读
- java - 在 Java 中使用函数式接口的真实示例
- r - 是否有一个 R 函数用于连续计算相同的值?
- python - 在 Heroku 上部署的过程 - 主机上会发生什么?
- marklogic - 如何在 MarkLogic 中对文档中的数据进行非规范化?
- git - 如何在git中的多个分支之间同步
- eclipse-cdt - 液晶显示旧数据和新数据
- facebook-graph-api - 在没有 manage_pages 权限的情况下从 facebook graph API 获取 instagram ID
- reactjs - Meteor 方法如何返回结果?
- angular - 获取 API 响应中的特定对象
- firefox - 如何在 Robot Framework 上打开 Firefox 53