简体   繁体   English

如何在 state 更新后使用 async/await 来读取我的道具(react.js)

[英]how to use async/await to allow my props to be read after state is updated (react.js)

I am trying to to pass down props to a react child component with information from an API, and I know the API information and all the syntax is correct because, if I don't refresh the page, all the information is there.我正在尝试使用来自 API 的信息将道具传递给反应子组件,并且我知道 API 信息并且所有语法都是正确的,因为如果我不刷新页面,所有信息都在那里。 But as soon as I Do, an error is thrown saying it "can't read property '...' undefined"但是一旦我这样做,就会抛出一个错误,说它“无法读取属性'...'未定义”

This is the parent Component:这是父组件:

function TeamList() {
    const [URL, setURL] = useState('http://api.football-data.org/v2/teams/86/')
    const [team, setTeam] = useState([])
    const [teamName, setTeamName] = useState('Manchester United')
    async function getTeam() {
        setURL('http://api.football-data.org/v2/teams/86/')


        try {
        const response = await axios.get(`${URL}`, {
            headers: {
                'X-Auth-Token': '#'
            }
        })
        setTeamName(response.data.name)
        setTeam(response.data)

        } catch (error) {
            console.error(error);
        }
    }


        useEffect(async() => {
            getTeam()
        }, [])

    return (
        <div className="Team">
            <h4> {teamName} </h4>
            <Team 
                activeComps = {team.activeCompetitions}
                address = {team.address}
                crest = {team.crestUrl}
                email = {team.email}
                founded = {team.founded}
                teamID = {team.id}
                tla = {team.tla}
                venue = {team.venue}
                website = {team.website}
                squad = {team.squad}
            />
        </div>
    )   
}

export default TeamList

This is the Child Component:这是子组件:

function Team(props) {
    return (
        <div className="Team" id={props.teamID}>
            <img src={props.crest} />
            <h5>Founded: {props.founded}</h5>
            <h5>Current Competitions</h5>
                <ul>
                    <li> <Link to ="/league">{props.activeComps[0].name}</Link></li>
                    <li> <Link to ="/league">{props.activeComps[1].name}</Link></li>
                </ul>
            <h5>Team Address: </h5>
            <p>{props.address}</p>
            <h5>Venue: </h5>
            <p>{props.venue}</p>
            <h5>Website: </h5>
            <p>{props.website}</p>
      
        </div>
    )
}

export default Team

The first issue is that you're defaulting team to an empty array, but it seems to be an object when it's returned from the API call.第一个问题是您将team默认为一个空数组,但是当它从 API 调用返回时,它似乎是一个 object。 To simplify things, we can just default it to undefined .为了简化事情,我们可以将其默认为undefined

const [team, setTeam] = useState();

The second issue, which is causing the errors you're hitting, is that you're trying to render the Team component before you have your data.导致您遇到的错误的第二个问题是您试图在获得数据之前呈现Team组件。 To prevent this from happening, you can use a ternary operator to show a loading status while you're team is undefined (note that this recommendation only really works if you take my previous recommendation):为防止这种情况发生,您可以在team未定义时使用三元运算符来显示加载状态(请注意,此建议仅在您接受我之前的建议时才真正有效):

{team ? <Team 
  activeComps = {team.activeCompetitions}
  address = {team.address}
  crest = {team.crestUrl}
  email = {team.email}
  founded = {team.founded}
  teamID = {team.id}
  tla = {team.tla}
  venue = {team.venue}
  website = {team.website}
  squad = {team.squad}
/> : "Loading..."}

Also, I would probably recommend just passing the whole team object down to the Team component;另外,我可能会建议将整个team object 传递给Team组件; that would really simplify the interface.这将真正简化界面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM