首页 > 解决方案 > 无法使用 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

标签: javascriptreactjsreact-hooks

解决方案


我认为你做错的是你在另一个对象中保存和对象

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

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

errors:{"hi","bye"}

推荐阅读