简体   繁体   English

无法使用 useState 更新状态

[英]Can't update state using useState

I'm trying to update the state of my component with useState in a register functional component。 when user input an invalid email address and click the submit button, the following piece of code will return an error message我正在尝试使用注册功能组件中的 useState 更新我的组件的状态。 当用户输入无效的电子邮件地址并单击提交按钮时,以下代码将返回错误消息

let response= await axios.post("/api/user/register",new_user,config);

I want to set error message into formData with this piece of code .我想用这段代码将错误消息设置为 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);
        }

but the value of errors is empty,like this但是错误的值为空,就像这样结果截图

What should I do to set error message into formData?我应该怎么做才能将错误消息设置为 formData?

Here is my code:这是我的代码:

 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

I think what you are doing wrong is that you are saving and object inside another object我认为你做错的是你在另一个对象中保存和反对

const [formData,setFormData]=useState({
    name:"",
    email:"",
    password:"",
    password2:"",
    errors:{}
});

formData is an object while errors is also an object.To go for a better approach make a seperate state for errors and append all the errors coming through those messages in an error object. formData 是一个对象,而错误也是一个对象。为了寻求更好的方法,为错误创建一个单独的状态,并将通过这些消息传入的所有错误附加到一个错误对象中。 If you write a message in errors object where it is defined it will give you error如果你在定义它的错误对象中写一条消息,它会给你错误

errors:{"hi","bye"}

There is no issue in your code.您的代码没有问题。 What you are trying to do is console the state as soon as you are setting it up.您要做的是在设置state立即对其进行控制台。

setState is asynchronous which means you can't call it on one line and assume the state has changed on the next. setState是异步的,这意味着您不能在一行调用它并假设状态在下一行发生了变化。

If you check React docs如果你查看React 文档

setState() does not immediately mutate this.state but creates a pending state transition. setState()不会立即改变this.state而是创建一个挂起的状态转换。 Accessing this.state after calling this method can potentially return the existing value.调用此方法后访问this.state可能会返回现有值。 There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.无法保证对 setState 调用的同步操作,并且可能会批量调用以提高性能。

I'd suggest you use useEffect and then check for change in data of your state.我建议您使用useEffect然后检查您的状态数据的变化。

useEffect(() => {
console.log(formData)
}, [formData])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM