React:将数组赋值给变量,使用useState传递给modal



我为即将到来的NFL赛季制作了一个JSON文件。在这个组件中,我有一个工作的获取方法来获取我的数据,并且我将变量命名为"squad"。现在我想按下一个按钮来过滤掉所选团队的日程安排,并在一个模式中显示它。在这个例子中,我对按钮进行了硬编码。我的模态组件工作得很好,我有{props。

在下面的代码中,您将看到我正在尝试使用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>
);
})}

相关内容

  • 没有找到相关文章

最新更新