我有一个包含名称,电子邮件和密码的登录表单。我已经做了相同的验证。我的要求是,仅在验证成功后才提交表单。检查以下代码,
const [error, setError] = useState(false);
const [errorEmail, setEmailError] = useState(false);
const [errorMsg, setMsgState] = useState({
name : "",
email : "",
password : ""
});
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const dispatch = useDispatch();
const handleSubmit = e => {
e.preventDefault();
if (name.trim() === '') {
setError(true);
setMsgState(prevState => ({
...prevState,
name: '* Name required'
}))
}
if (email.trim() === '') {
setError(true);
setMsgState(prevState => ({
...prevState,
email: '* Email required'
}))
}
if (password.trim() === '') {
setError(true);
setMsgState(prevState => ({
...prevState,
password: '* Password required'
}))
}
if (email.trim() !== '') {
if (!/^[a-zA-Z0-9]+@[a-zA-Z0-9]+\.[A-Za-z]+$/.test(email)) {
setEmailError(true);
setMsgState(prevState => ({
...prevState,
email: '* Enter valid email'
}))
}
else
setEmailError(false);
}
if (!error && !errorEmail) {
const user = { name, email, password };
dispatch(authenticate(user));
}
};
在上面的代码中,当用户第一次单击“提交”按钮时,将显示验证消息,并且也在提交表单。第二次是不提交表单,仅显示验证消息。 State is not updating immediately
。如何更改我的代码以实现此目的?
答案 0 :(得分:2)
在useEffect挂钩中添加错误检查,
let mysql = require('mysql');
let connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'password!',
database: 'database_name',
multipleStatements: true
});
let sql = `SELECT * FROM table01; SELECT * FROM table02`;
connection.query(sql, (error, results, fields) => {
if (error) {
return console.error(error.message);
}
console.log(results[0]);
console.log(results[1]);
});