首页 > 解决方案 > 列表中的每个孩子都应该有一个唯一的“关键”道具。检查 `Form` 的渲染方法

问题描述

对此警告消息有一些问题。我通常从另一个组件渲染列表并将“key”的键作为 id 属性传递。但是,如果我尝试分配键,则会收到一条错误消息,指出键值不存在。新的反应和有点难倒这个。有任何想法吗?

import React, {useState, useEffect} from "react";
import * as yup from "yup";
import axios from "axios";
/* Name
 Email
 Password
 Terms of Service (checkbox)
 A Submit button to send our form data to the server.*/
let schema = yup.object().shape({
    user: yup.string().required("Please Enter Name"),
    email: yup.string().required("Please Enter an email Address").email(),
    password: yup.string().required("Please Enter a password").min(8, "Enter at least 8 Characters"),
    passwordConfirmation: yup.string().oneOf([yup.ref('password'), null], 'Passwords must match'),
    TermsOfService: yup.boolean().required("Please Agree to the Terms of Service"),

})

export default function Form()
{
    const [users, setUsers] = useState([]);

    const initialFormValues = 
    {
        user: "",
        email: "",
        password: "",
        passwordConfirmation: "",
        TermsOfService: false
    }

    const [form, setForm] = useState(initialFormValues);

    const [errors, setErrors] = useState({
        user: "",
        email: "",
        password: "",
        passwordConfirmation: "",
        TermsOfService: false
    });

    const [disabled, setDisabled] = useState(true);
    
    const setFormErrors = (name, value) => {
        //console.log(name)
        yup
        .reach(schema, name)
        .validate(value)
        .then(() => setErrors({...errors, [name]: ""}))
        .catch((err) => setErrors({...errors, [name]: err.errors[0]}))
    }

    const onChange = (e) => 
    {
        const { name, type, value, checked } = e.target;

        const realValue = type === "checkbox" ? checked : value;

        setFormErrors(name, realValue);
        setForm({...form, [name]: realValue });
        console.log(`${name} of type ${type} has changed to ${realValue}`)
    };
    const submit = (e) => {
        e.preventDefault();
        
        const newUser = {
            user: form.user.trim(),
            email: form.email.trim(),
            password: form.password.trim(),
            passwordConfirmation: form.passwordConfirmation.trim(),
            TermsOfService: true
        };
        
        axios
            .post("https://reqres.in/api/users", newUser)
            .then((res) => {
                setForm(initialFormValues);
                console.log(res.data)
                setUsers([...users, res.data]);
            })
            .catch((err) => {
                debugger;
            });
    };
        //console.log("this part is working")
    return(
        <div>
        <form className="form container" onSubmit={submit}>
    <div className = "form box">

    <label>
        User:
        <input type = "text" name = "user" value = {form.user} onChange={onChange}/>
    </label>
    
    <label>
        Email:
        <input type="text" name="email" value = {form.email} onChange={onChange}/>
    </label>

    <label> 
        Password:
            <input type="text" name="password" value = {form.password} onChange={onChange}/>
    </label>

    <label>
        Password Confirmation:
        <input type = "text" name = "passwordConfirmation" value = {form.passwordConfirmation} onChange={onChange}/>
    </label>
    
    <label>
        Terms of Service
        <input type = "checkbox" name = "TermsOfService" value = {form.TermsOfService} onChange={onChange}/>
    </label>

    </div>
    <div className="submitButton">
        <button>Submit</button>
    </div>
            </form>
     {users.map(user =>
        {   
            return(
                <>
                   
                    <p> User Name :{user.user}</p>
                    <p>User Email :{user.email}</p>
                </>
                )
        })}
        </div>
    )
}

标签: javascriptreactjspoststate

解决方案


如果您不想要包装器并想要分配属性,请使用 key React.Fragment

{users.map(user => {   
        return(
            <React.Fragment key={user.user}>
                <p> User Name :{user.user}</p>
                <p>User Email :{user.email}</p>
            </React.Fragment>
        )
 })}

推荐阅读