React:使用useState将数组分配给变量以传递给模态

React: Assigning array to variable using useState to pass into modal

我为即将到来的 NFL 赛季制作了 JSON 文件。在这个组件中,我有一个获取数据的有效获取方法,我将变量命名为“squads”。现在我想按一个按钮来过滤出所选团队的日程安排并以模式显示。我在这个例子中硬编码了我的按钮。我的模态组件工作正常,模态主体中有 {props.children} 来接受我的数据。

在下面的代码中,您会看到我正在尝试使用 useState 将过滤后的团队分配给 selectedTeam 变量。我收到的错误消息只是说我的变量未定义。

import React, { useState, useEffect } from "react";
import Modal from "./Components/Modal";

export default function App() {
  const [show, setShow] = useState(false);
  const [title, setTitle] = useState("");
  const [squads, setSquads] = useState([]);
  const [modalTitleBackground, setModalTitleBackground] = useState("");
  const [image, setImage] = useState("");
  const [selectedTeam, setSelectedTeam] = useState([]);

  const url = "../nfl2021.json";

  const fetchData = async () => {
    try {
      const response = await fetch(url);
      const data = await response.json();
      setSquads(data.teams);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // const filterTeam = (team) => {
  //   const theTeam = squads.filter((squad) => squad.name === team);
  //   setModalTitleBackground(theTeam[0].topBG);
  //   // setTitle(theTeam[0].name);
  //   setNickname(theTeam[0].nickname);
  //   setImage(`./images/${theTeam[0].img}`);
  //   setShow(true);
  // };

  const filterTeam = (team) => {
    setSelectedTeam(squads.filter((squad) => squad.name === team));
    console.log(selectedTeam);
    setTitle(selectedTeam[0].name);
    setModalTitleBackground(selectedTeam[0].topBG);
    setImage(`./images/${selectedTeam[0].img}`);
    setShow(true);
  };

  return (
    <div className="App">
      <button onClick={() => filterTeam("New England Patriots")}>
        Show Modal
      </button>
      <button onClick={() => filterTeam("Green Bay Packers")}>
        Show Modal 2
      </button>
      <button onClick={() => filterTeam("Cincinnati Bengals")}>
        Show Modal 3
      </button>
      <Modal
        image={image}
        title={title}
        backgroundColor={modalTitleBackground}
        onClose={() => setShow(false)}
        show={show}
      >
        <p>
          This is the modal body using props.children in the modal component.
        </p>
        <p>The {title} 2021 schedule.</p>

        {selectedTeam[0].schedule.map((schedule, index) => {
          return (
            <p>
              Week {index + 1}: The {selectedTeam[0].nickname} play the{" "}
              {selectedTeam[0].schedule[index].opponent}.
            </p>
          );
        })}
      </Modal>
    </div>
  );
}

1-在react中,状态是异步设置的。 selectedTeam 直到下一次渲染才设置。

2- 您可以使用 find 而不是 filter 并摆脱数组访问。

const [selectedTeam, setSelectedTeam] = useState({schedule: []});

...

const filterTeam = (team) => {
    let temp = squads.find((squad) => squad.name === team);
    setSelectedTeam(temp);
    console.log(temp);
    setTitle(temp.name);
    setModalTitleBackground(temp.topBG);
    setImage(`./images/${temp.img}`);
    setShow(true);
};

...

    {selectedTeam.schedule.map((match, index) => {
      return (
        <p>
          Week {index + 1}: The {selectedTeam.nickname} play the {match.opponent}.
        </p>
      );
    })}