使用 useEffect 从 api 获取数据

时间:2021-07-28 09:08:04

标签: reactjs react-hooks use-effect

我正在尝试获取排名信息,从 api 匹配信息,它使用 useEffect 工作,我能够将数据转换为 jsx 并且它工作正常,但由于某种原因匹配 prop传递给 Matches 组件在它被渲染时总是 null 即使当我在它作为道具传递之前控制台记录它时它包含 jsx 数组???

这是我的主要组件,用于呈现比赛和排名

    function LeagueView(){
    const param = useParams();
    const [standings , setStandings] = useState(); 
    const [matches , setMatches] = useState();
    useEffect(async () =>{
        try{
            const standingsRes = await getLeagueStandings(param.leagueId);
            const s = standingsToJSX(standingsRes);
            console.log(s)
            setStandings(s);

            const mathesRes = await getLeagueMatches(param.leagueId);
            const m =  matchesToJSX(mathesRes);
            console.log(m);
            setMatches(m);
            
        }catch(err){
            console.error(`${err.message} LeagueView.js`);
            setStandings(null);
            setMatches(null);
        }
        
    } 
    
    , [matches , standings]);
    
    

    console.log(matches);
    return(
        <div>
            <Standings standings = {standings}/>
            <Matches matches = {matches}/>
        </div>
    )
}
export default LeagueView;

这是匹配组件

   class Matches extends React.Component{
    constructor(props){
        super(props);
        console.log(props.matches);
        this.state = {
            matches : props.matches
        }
    }

    render(){
        return(
            <div className = {`${classes.matchesRoot}`}>
                {this.state.matches ? this.state.matches : <Message msg = 'Cant Retrieve League Matches'/>}
            </div>
        )
    }
}

export default Matches;

0 个答案:

没有答案