我正在编写一个完整的Web应用程序来注册用户。我有状态变量来反映后端错误,然后在jsx代码中使用它们。每当alerts
更改时,我都会重新渲染组件(这是由Redux管理的应用程序级状态,其内容由后端生成)。我面临的问题是,当我第一次不输入所需信息并点击“提交”时,我会在错误输入的字段下方成功显示错误1秒钟,然后分派明确的警报措施,尽管{{1 }}状态是根据redux devtool更新的,该错误消息在组件中1 s后仍会存在。我认为问题在于我需要重置与已清除的字段相对应的局部状态变量,但是我不确定如何实现。错误在下面的alerts
状态变量中捕获。这是我的组件
errorsData
答案 0 :(得分:0)
您的组件设置不正确,因为在必须使用connect
和useDispatch
进行功能组件的还原时,您尝试将useTypedSelector
与功能组件一起使用。相反,您应该这样做。
import React, { useState, useEffect } from "react";
/* Hooks */
**import { useDispatch, useSelector } from "react-redux";**
/* Actions */
import { registerUser } from "../../actions/auth";
import { setAlert } from "../../actions/alert";
const Register = () => {
// Hooks
**const dispatch = useDispatch();**
// Store
**const alerts = useSelector(state => state.alert);**
// Local state
const [formData, setFormData] = useState({
name: "",
email: "",
password: "",
password2: "",
});
const [errorsData, setErrorsData] = useState({
nameErr: "",
emailErr: "",
passwordErr: "",
});
const { name, email, password, password2 } = formData;
const { nameErr, emailErr, passwordErr } = errorsData;
// Event handlers
const handleOnChange = e => setFormData({ ...formData, [e.target.name]: e.target.value });
const handleOnSubmit = async e => {
e.preventDefault();
if (password !== password2) console.log("Passwords do not match");
else dispatch(registerUser({ name, email, password }));
};
// Effects
useEffect(() => {
alerts.forEach(alert => {
switch(alert.errField) {
case "name":
setErrorsData({ ...errorsData, nameErr: alert.msg });
break;
case "email":
setErrorsData({ ...errorsData, emailErr: alert.msg });
break;
case "password":
setErrorsData({ ...errorsData, passwordErr: alert.msg });
break;
default:
break;
};
});
}, [alerts, errorsData]);
// Rendering
return (
<form className="form" onSubmit={handleOnSubmit}>
<div className="input-field">
<label htmlFor="name">Name</label>
<input
type="text"
name="name"
value={name}
id="name"
placeholder="Enter your name"
onChange={handleOnChange}
/>
<small className="error error--name">{nameErr}</small>
</div>
<div className="input-field">
<label htmlFor="email">Email</label>
<input
type="email"
name="email"
value={email}
id="email"
placeholder="Enter a valid email"
onChange={handleOnChange}
/>
<small className="error error--email">{emailErr}</small>
</div>
<div className="input-field">
<label htmlFor="password">Passwrod</label>
<input
type="password"
name="password"
value={password}
id="password"
placeholder="Enter password"
onChange={handleOnChange}
/>
<small className="error error--password">{passwordErr}</small>
</div>
<div className="input-field">
<label htmlFor="password2">Confirm password</label>
<input
type="password"
name="password2"
value={password2}
id="password2"
placeholder="Confirm password"
onChange={handleOnChange}
/>
</div>
<input className="submit" type="submit" value="Submit" />
</form>
);
};
**export default Register;**
突出显示主要更改。