无法使用useState更新状态

时间:2020-09-05 04:37:19

标签: javascript reactjs react-hooks

我正在尝试使用寄存器功能组件中的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);
        }

但是错误的值是空的,例如result screenshot

如何将错误消息设置为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

2 个答案:

答案 0 :(得分:0)

我认为您做错了,是您在另一个对象中保存对象并将其保存

Resources:

  DBSecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: Database security group
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: '3306'
          ToPort: '3306'
          SourceSecurityGroupId: !ImportValue PatheinWebServerSecurityGroupId

formData是一个对象,而错误也是一个对象。要寻求更好的方法,请为错误创建单独的状态,并将通过这些消息传递的所有错误附加到错误对象中。 如果您在错误对象的定义位置写了一条消息,它将给您错误

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

答案 1 :(得分:0)

您的代码没有问题。您要尝试做的就是在设置state后立即对其进行控制台。

setState是异步的,这意味着您不能在一行上调用它,而假定状态在下一行上已更改。

如果您选中React docs

setState()不会立即使this.state突变,但会创建一个挂起的状态转换。调用此方法后访问this.state可能会返回现有值。无法保证对setState调用的同步操作,并且可能会批量调用以提高性能。

我建议您使用useEffect,然后检查您所在州的数据是否更改。

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