问题描述
我正在尝试构建一个注册表单,我已经构建了登录表单,它可以正常运行,但是注册表单还不完善。
-
首先,我使用
react-dev
工具检查发生了什么,我意识到来自 registration 表单的每个input
值都位于array
。 -
我返回到登录表单进行检查,发现
input
字段的值格式正确(strings
)。但是注册表单中每个特定input
字段的值都在array
中。 我可能做错了什么?
这是我从react-dev
工具注册表格中看到的。
这是我所做的代码段。
const Signup = (props) => {
const authContext = useContext(AuthContext);
const { register,clearErrors,isAuthenticated,error } = authContext;
const [loadBtn,updateLoadBtn] = useState(false);
const [user,setUser] = useState({
firstName: "",lastName: "",email: "",password: "",username: "",phoneNumber: "",});
useEffect(() => {
if (isAuthenticated) {
successMessage();
props.history.push("/dashboard");
}
if (error) {
missingValue(error);
updateLoadBtn(false);
clearErrors();
}
//eslint-disable-next-line
},[isAuthenticated,error,props.history]);
const { firstName,lastName,email,password,username,phoneNumber } = user;
const onChange = (e) =>
setUser({ ...user,[e.target.name]: [e.target.value] });
const onSubmit = (e) => {
e.preventDefault();
updateLoadBtn(true);
if (
!firstName ||
!lastName ||
!email ||
!password ||
!username ||
!phoneNumber
) {
missingValue("Please enter all fields");
updateLoadBtn(false);
clearErrors();
} else {
register({
firstName,phoneNumber,});
}
};
return (
<Fragment>
<ToastContainer />
<RegContainer className="container-fluid py-4">
<RegInfo />
<RegColumn
onChange={onChange}
onSubmit={onSubmit}
firstName={firstName}
lastName={lastName}
email={email}
password={password}
phoneNumber={phoneNumber}
loadBtn={loadBtn}
/>
</RegContainer>
</Fragment>
);
}
这是自定义组件
const RegColumn = ({
firstName,onSubmit,onChange,loadBtn,}) => {
const bodyStyle = document.querySelector("body").style;
bodyStyle.backgroundImage = "linear-gradient(to bottom,#F6F6F2,#C2EDCE)";
bodyStyle.backgroundRepeat = "no-repeat";
bodyStyle.overflow = "hidden";
bodyStyle.height = "100%";
bodyStyle.fontFamily = "Rubik,sans-serif";
return (
<Fragment>
<div id="reg-column">
<h3 style={{ color: "#388087" }}>REGISTRATION</h3>
<Form divid="form-row1-label" onSubmit={onSubmit}>
<LabelContainer id="form-row1-label">
<LabelContainer id="firstNameLabel">
<LabelInfo labelfor="firstName" labeltitle="First Name" />
</LabelContainer>
<LabelContainer id="lastNameLabel">
<LabelInfo labelfor="lastName" labeltitle="Last Name" />
</LabelContainer>
</LabelContainer>
<InputContainer id="form-row1-input">
<InputContainer id="firstNameInput">
<Input
type="text"
name="firstName"
value={firstName}
id="firstName"
onChange={onChange}
/>
</InputContainer>
<InputContainer id="lastNameInput">
<Input
type="text"
onChange={onChange}
name="lastName"
value={lastName}
id="lastName"
/>
</InputContainer>
// ...
谢谢。
解决方法
在您的Signup
表格中,您有这个...
// ...
const onChange = (e) =>
setUser({ ...user,[e.target.name]: [e.target.value] });
上面发生了什么事?
-
onChange()
负责更新要提交的值。 - 在
setUser
内,您正在使用array
传递值作为文字[e.target.value]
解决方案:
- 删除文字数组
[]
并在接收到值时传递值,即e.target.value
- 左侧
e.target.name
很好,因为您实际上是在使用computed property name。
您还可以了解有关handling forms in react的更多信息。