【问题标题】:React: Assigning array to variable using useState to pass into modalReact:使用useState将数组分配给变量以传递给模态
【发布时间】:2021-10-28 14:23:07
【问题描述】:

我为即将到来的 NFL 赛季制作了一个 JSON 文件。在这个组件中,我有一个有效的 fetch 方法来获取我的数据,并且我将变量命名为“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>
  );
}

【问题讨论】:

    标签: arrays reactjs modal-dialog prop


    【解决方案1】:

    1- 在反应中,状态是异步设置的。 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>
          );
        })}
    

    【讨论】:

    • 回文,我更改了 filterTeam 函数以反映您的答案,这解决了部分问题。如果我在返回中注释掉我的 map 方法,我可以在单击按钮时 console.log 正确的值。所以我然后将我的地图函数更改为在selectedTeam 上进行映射,然后我得到 selectedTeam.map 不是函数。
    • @JohnG.我错过了那部分,抱歉。此修改应该可以修复它。
    • 回文,成功了!非常感谢您花时间帮助我。这是我的第一个 React 应用程序,我知道必须有一个答案。看起来我很接近,但我无法弄清楚。
    • 成功了!非常感谢您花时间帮助我。这是我的第一个 React 应用程序,我知道必须有一个答案。看起来我很接近,但我无法弄清楚
    • 正在尝试这样做。不工作。怎样才能让对方的topBG回归? ``` {selectedTeam.schedule.map((match, index) => { return (

      Week {index + 1}: {selectedTeam.nickname} 播放{" "} {match.opponent},其背景颜色是{" "} {getBackground(match.opponent)}

      ); })} ```
    猜你喜欢
    • 2019-08-11
    • 2020-06-01
    • 2023-03-18
    • 2022-08-21
    • 2020-05-22
    • 2017-07-23
    • 2020-08-16
    • 1970-01-01
    • 2018-06-27
    相关资源
    最近更新 更多