我试图把我的表单给一个新的页面。问题是他们唯一的id不被接受,我不知道为什么。
表格代码:
import { useState } from "react";
import { useForm } from "react-hook-form";
import { useLocalStorage } from "react-use";
import useLocalStorageState from "use-local-storage-state";
import { v4 as uuidv4 } from "uuid";
import AnimalDetails from "./AnimalDetails";
export default function AddAnimalForm() {
const [animalData, setAnimalData] = useLocalStorage("Animal Data", []);
const [animals, setAnimals] = useLocalStorageState("animals", []);
const [submitMessage, setSubmitMessage] = useState(false);
const [showDetails, setShowDetails] = useState(false);
const { register, handleSubmit, formState: { errors } } = useForm();
const onSubmit = (data, event) => {
event.target.reset();
const id = uuidv4();
const newAnimalData = { ...data, id: id };
setAnimalData([...animalData, newAnimalData]);
setAnimals([...animals, newAnimalData]);
setSubmitMessage(true);
setShowDetails(true);
setTimeout(() => {
setSubmitMessage(false);
setShowDetails(false);
}, 3000);
};
return (
<div>
<form onSubmit={handleSubmit(onSubmit)}>
<select {...register("species", { required: true })}>
<option value="">--Choose Animal--</option>
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="rabbit">Rabbit</option>
<option value="tortoise">Tortoise</option>
<option value="guinea pig">Guinea pig</option>
</select>
{errors.species && <span>Species is required</span>}
<ul>
<input {...register("name", { required: true })} key="name" placeholder="Name" />
{errors.name && <span>Name is required</span>}
<input {...register("age", { required: true })} key="age" placeholder="Age" />
{errors.age && <span>Age is required</span>}
<input {...register("character", { required: true })} key="character" placeholder="Character" />
{errors.character && <span>Character is required</span>}
<input {...register("owner", { required: true })} key="owner" placeholder="Owners" />
{errors.owner && <span>Owners is required</span>}
<input {...register("miscellaneous")} key="miscellaneous" placeholder="miscelleaneous" />
</ul>
<input type="submit" />
</form>
{submitMessage && <p>Form submitted successfully</p>}
{showDetails && <AnimalDetails animals={animals} />}
</div>
);
}
应该呈现所有输入信息的页面代码:
import React from "react";
export default function AnimalDetails({ animals }) {
return (
<div>
<h2>Animal Details</h2>
{animals.map((animal) => (
<div key={animal.id}>
<p>Species: {animal.species}</p>
<p>Name:{animal.name}</p>
<p>Age: {animal.age}</p>
<p>Character: {animal.character}</p>
<p>Owner: {animal.owner}</p>
<p>Miscellaneous: {animal.miscellaneous}</p>
</div>
))}
</div>
);
}
我以为给我的div一个关键元素就足够了,但之后我得到了以下错误:
警告:列表中的每个子元素都应该有唯一的“键”属性。
1条答案
按热度按时间nfs0ujit1#