[英]Pulling data from function and adding it to a global variable in Javascript
I'm building a webapp in React.js and I'm trying to pass data from a child component back up to the parent.我正在 React.js 中构建一个 webapp,我正在尝试将数据从子组件传递回父组件。 I am passing the data back up successfully but can't manage to extract the relevant data to become a global variable.
我将数据成功备份,但无法提取相关数据成为全局变量。 I would really appreciate anyone's help.
我真的很感激任何人的帮助。 I know that I am returning the correct data based on the console.log.
我知道我正在根据 console.log 返回正确的数据。
I am trying to extract 'data' from the 'pull_data' function and add it to the global 'year' variable.我正在尝试从“pull_data”function 中提取“数据”并将其添加到全局“年份”变量中。
Here is my code:这是我的代码:
import React, { useEffect, useState, useContext } from "react";
import { useAuthState } from "react-firebase-hooks/auth";
import { useNavigate } from "react-router-dom";
import { auth } from "../firebase";
import Header from "../components/headerTeamList";
import Grid from "@material-ui/core/Grid";
import { makeStyles } from "@material-ui/core/styles";
import TeamList from "../components/teamList";
import { getTeams } from "../api/football-api";
import Menu from "../components/dropdownMenu";
const useStyles = makeStyles({
root: {
padding: "60px",
},
});
function Dashboard() {
const [user, loading, error] = useAuthState(auth);
const navigate = useNavigate();
const classes = useStyles();
const [teams, setTeams] = useState([]);
const pull_data = (data) => {
console.log(data);
return data;
}
const year = 2016 //need to update
useEffect(() => {
if (loading) return;
if (!user) return navigate("/");
}, [user, loading]);
useEffect(() => {
getTeams(year).then((json) => {
setTeams(json.response[0].league.standings[0]);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [year]);
return (
<Grid container className={classes.root}>
<Grid item xs={12}>
<Header title={"Home Page"} />
<Menu func={pull_data}></Menu>
</Grid>
<Grid item container spacing={5}>
<TeamList teams={teams}></TeamList>
</Grid>
</Grid>
);
}
export default Dashboard;
You can make year
a state variable and set it from pull_data
:您可以将
year
设为 state 变量并从pull_data
设置它:
const [year, setYear] = useState(2016)
const pull_data = data => {
setYear(data)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.