javascript - 无法使用 useState 更新状态
问题描述
我正在尝试在注册功能组件中使用 useState 更新我的组件的状态。当用户输入无效的电子邮件地址并单击提交按钮时,以下代码将返回错误消息
let response= await axios.post("/api/user/register",new_user,config);
我想用这段代码将错误消息设置到 formData 中。
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
但是errors的值是空的,像这样
我应该怎么做才能将错误消息设置为formData?
这是我的代码:
import React ,{useState}from 'react'
import axios from "axios"
function Register() {
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
const {name,email,password,password2}=formData;
const setValue= e =>setFormData({...formData,[e.target.name]:e.target.value})
const submitData=async (e) =>{
e.preventDefault();
if(password!==password2){
console.log("passwords do not match ");
}else{
let new_user={name,email,password,}
try{
let config={
header:{
'Content-Type':'applicaiton/json'
}
}
let response= await axios.post("/api/user/register",new_user,config);
if(response.data.errnum!==0){
setFormData({...formData,errors:response.data.message})
console.log(formData);
}
}catch(error){
console.error(error);
}
}
}
return (
<div>
<section className="container">
<h1 className="large text-primary">Sign Up</h1>
<p className="lead"><i className="fas fa-user"></i> Create Your Account</p>
<form className="form" onSubmit={e=>submitData(e)}>
<div className="form-group">
<input
type="text"
placeholder="Name"
name="name"
value={name}
onChange={e=>setValue(e)}
required />
</div>
<div className="form-group">
<input
type="email"
placeholder="Email Address"
onChange={e=>setValue(e)}
value={email}
name="email" />
<small className="form-text">This site uses Gravatar so if you want a profile image, use aGravatar email</small>
</div>
<div className="form-group">
<input
type="password"
placeholder="Password"
onChange={e=>setValue(e)}
value={password}
name="password"
minLength="6"
/>
</div>
<div className="form-group">
<input
type="password"
placeholder="Confirm Password"
onChange={e=>setValue(e)}
value={password2}
name="password2"
minLength="6"
/>
</div>
<input type="submit" className="btn btn-primary" value="Register" />
</form>
<p className="my-1">
Already have an account? <a href="login.html">Sign In</a>
</p>
</section>
</div>
)
}
export default Register
解决方案
我认为你做错的是你在另一个对象中保存和对象
const [formData,setFormData]=useState({
name:"",
email:"",
password:"",
password2:"",
errors:{}
});
formData 是一个对象,而errors 也是一个对象。要寻求更好的方法,请为错误创建一个单独的状态,并将通过这些消息出现的所有错误附加到一个错误对象中。如果你在定义它的错误对象中写一条消息,它会给你错误
errors:{"hi","bye"}
推荐阅读
- html - 如何使用谷歌材料设计图标进行 HTML 图像控件而不是图像 url?
- sql-server - 在具有父子关系的同一张表上使用多个子选择进行选择
- python - Tensorflow 2.0 将 keras 模型转换为 .pb 文件
- python - 在 DataFrame 中将字符串转换为整数
- spring-boot - Spring Boot + Hibernate Search:忽略所需的索引状态?
- python - dict中元组的莫名长度
- mysql - 应该向哪个添加 shipping_charges?
- python - 修剪字符串直到任何指定的字符
- mysql - 为什么这个更新声明没有更新?
- socket.io - 将从一个 socket.io 服务器接收到的数据发送到 Web 套接字客户端