javascript 将结果从一个React JS函数传递到另一个React JS函数

dkqlctbz  于 2023-05-05  发布在  Java
关注(0)|答案(1)|浏览(134)

我试图从Home函数访问'getServerSideProps'函数返回的数据以显示结果,但我没有任何运气。有没有人能提供一些建议?
为了尽可能清楚,getServerSideProps()在指定的播放列表中查找视频列表,我试图将数据传递给home函数以显示结果。我不得不从getServerSideProps()中删除导出;否则,该函数将console.log一个未定义的响应。

import React, { useState, useEffect } from 'react';
import './Home.css'
//Components
import Header from '../../Components/Header/Header';
import Footer from '../../Components/Footer/Footer';
//Repositories
import { Navigate } from 'react-router-dom';

const YouTube_Playlist_Items_API = process.env.REACT_APP_YouTube_PlayList_Item_API_URL;
const YouTube_Key = process.env.REACT_APP_YouTube_API_KEY;
const YouTube_Playlist_ID = process.env.REACT_APP_YouTube_PlayList_Item_ID;
const YouTube_MaxResults = process.env.REACT_APP_YouTube_PlayList_Max_Results;

const getServerSideProps = async () => {
    const res = await fetch(`${YouTube_Playlist_Items_API}?part=snippet&playlistId=${YouTube_Playlist_ID}&maxResults=${YouTube_MaxResults}&key=${YouTube_Key}`);
    const data = await res.json();
    console.log('data', data);
    return {
        props: {
          data
        }
    }
}

const Home = () => {
    getServerSideProps();
    return (
        <>
            <Header/>
            <div className='homeBody'>
                <p>Hello</p>
            </div>
            <Footer />
        </>
    );
}

export default Home;
olhwl3o2

olhwl3o21#

useState是我的问题的解决方案。

// declare useState data
    const [YTData, setYTData] = useState([]);
    const [isLoading, setIsLoading] = useState(false);

    //Declare the async data fetching function
    const getServerSideProps = async () => {
        setIsLoading(true);
        //Get the data from the api
        fetch(`${YouTube_Playlist_Items_API}?part=snippet&playlistId=${YouTube_Playlist_ID}&maxResults=${YouTube_MaxResults}&key=${YouTube_Key}`)
        //Convert data to json
        .then((res) =>  res.json())
        .then((data) => {
        setYTData(data.items);
        setIsLoading(false);
        })
        .catch((error) => {
            console.log(error);
            setIsLoading(false);
        })
    }

    useEffect(() => {
        getServerSideProps();
    }, []);

返回块:

return (
        <>
            <Header />
            <div className='homeBody'>
                {isLoading ? <h1>Loading...</h1> : YTData.map((obj) => <p>{obj.snippet.title}</p>)}
            </div>
            <Footer />
        </>
    );

相关问题