在两个函数之间传递道具会产生错误(道具未定义)

Passing props between two functions produces error (prop is undefined)

我正在使用 ReactJS 为网站制作模态。

我的问题:

我在两个不同页面(animals.js 上的动物和 AnimalModal.js 上的 AnimalModal)上的两个函数之间传递道具 animalName 以访问字典中的特定字段,以便模态他们每个人都显示不同的东西。我遇到了一个错误,"TypeError: Cannot read 属性 '2' of undefined," 但是我不确定我的错误在哪里。

我做了什么:

从控制台记录 currAnimal、majoranimals 字典的键和 animalName,我发现在 animals.js 页面上,一切似乎都很好,因为出现了与字典键对应的正确数字。但是,当我将该数字作为道具传递时,它不再适用于 AnimalModal.js,如果我要记录密钥或动物名称,我会得到“未定义”作为我的值。如果我单击以尝试使模式工作,则会弹出错误消息并且我的网站崩溃。同时,如果我只是将 AnimalModal.js 中的键设置为字典键范围内的整数,我可以获得该键的模态以正确显示。

我认为错误可能是:

我认为当我在函数之间传递 prop 时会出现问题,以下是我认为可能存在错误的代码片段。

在 animals.js 中(创建并传递道具 - 最有可能)

  const [currAnimal, setcurrAnimal] = React.useState(0);
            .sort()
            .map((key, index) => (
                <img
                  src={`${process.env.PUBLIC_URL}/animals/2021/${majoranimals[key][2]}`}
                  alt={key}
                  onClick={() => {
                    setOpen(true);
                    setcurrAnimal(key);
                  }}
                />
            ))}

      {/*Pass Information to Modal*/}
      <AnimalModal
        animalName={currAnimal}
      />

在AnimalModal.js(收到道具?)

const AnimalModal = ({ handleClose, animalName}) => {
  const key = parseInt(animalName);

感谢阅读!

您没有将 animalName 传递给 <AnimalModal handleClose={callbackModal} /> 这会导致您的应用程序崩溃。使此代码更易于理解的建议是更改

const majoranimals = {
      // name, website, img, type, description
      0: ["Dog",
          "websiteTBA", 
          "dog.png", 
          "animal", 
          "More information will be added shortly!"
          ],
      1: ["Cat",
          "websiteTBA", 
          "cat.png", 
          "animal", 
          "More information will be added shortly!"
          ],
      2: ["Bird",
          "websiteTBA", 
          "bird.png", 
          "animal", 
          "More information will be added shortly!"
          ],

  };

const majoranimals = {
      dog: {name: "Dog", 
            site: "websiteTBA",
            img: "dog.png", 
            type: "animal", 
            description: "More information will be added shortly!"
       }
     ...

  };

这样您就可以索引对象 majoranimals[key].img 而无需使用任意索引。您也无需再担心 parseInt 或保持排序。

从那里我会更改 AnimalModal 以更直接地获取它需要的信息作为道具。例如。 <AnimalModal information={majoranimals[key].information}。这样你就不需要在两个地方保存动物信息了。