gpt4 book ai didi

reactjs - 无法读取未定义 react 17 的属性 'map'

转载 作者:行者123 更新时间:2023-12-03 07:56:19 24 4
gpt4 key购买 nike

目前,我开始在 Udemy 类(class)“react-for-the-rest-of-us”中学习 react 。
现在,我试图从子组件接近状态钩子(Hook),我得到了上述错误。
我的目标是通过从用户输入中获取它的值来向状态添加另一个元素
这是父组件:

    import React, { useState } from "react";
import AddPetForm from "./FormPet";
function Header(props) {
const [pets, setPets] = useState([
{ name: "Meowsalot", species: "cat", age: "5", id: 123456789 },
{ name: "Barksalot", species: "dog", age: "3", id: 987654321 },
{ name: "Fluffy", species: "rabbit", age: "2", id: 123123123 },
{ name: "Purrsloud", species: "cat", age: "1", id: 456456456 },
{ name: "Paws", species: "dog", age: "6", id: 789789789 },
]);

const pet = pets.map((pet) => (
<Pet name={pet.name} species={pet.species} age={pet.age} id={pet.id} />
));
return (
<div>
<LikedArea />
<TimeArea />
<ul>{pet}</ul>
<AddPetForm set={setPets} />
</div>
);
}
function Pet(props) {
return (
<li>
{props.name}is a {props.species} and is {props.age} years old
</li>
);
}
这是子组件:
    import React, { useState } from "react";

function AddPetForm(props) {
const [name, setName] = useState();
const [species, setSpecies] = useState();
const [age, setAge] = useState();
console.log(props.set);
function handleSubmit(e) {
e.preventDefault();
props.set((prev) => {
prev.concat({ name: name, species: species, age: age, id: Date.now() });
setName("");
setSpecies("");
setAge("");
});
}

return (
<form onSubmit={handleSubmit}>
<fieldset>
<legend>Add New Pet</legend>
<input
value={name}
onChange={(e) => setName(e.target.value)}
placeholder="Name"
/>
<input
value={species}
onChange={(e) => setSpecies(e.target.value)}
placeholder="species"
/>
<input
value={age}
onChange={(e) => setAge(e.target.value)}
placeholder="age in years"
/>
<button className="add-pet">Add Pet</button>
</fieldset>
</form>
);
}

export default AddPetForm;

最佳答案

您没有返回新的串联数组。所以当你调用props.set应该是这样的:

props.set((prev) => {
setName("");
setSpecies("");
setAge("");
return prev.concat({ name: name, species: species, age: age, id: Date.now() });
});
如果您不返回任何内容,则从技术上讲,返回值为 undefined ,所以这就是它将状态设置为。然后,当您尝试 .map 时出现错误。它

关于reactjs - 无法读取未定义 react 17 的属性 'map',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64076133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com