无法读取未定义反应 17 的 属性 'map'

Cannot read property 'map' of undefined react 17

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

    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;

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

props.set((prev) => {
      setName("");
      setSpecies("");
      setAge("");
      return prev.concat({ name: name, species: species, age: age, id: Date.now() });
});

如果您没有 return 任何东西,那么从技术上讲,return 的值是 undefined,这就是它设置状态的原因。然后,当您尝试 .map it

时出现错误