P粉2079697872023-08-26 14:12:53
您需要在useEffect Hook中包裝非同步API調用,並將資料儲存在狀態中,以便在渲染函數中使用該狀態。以下是一個沒有測試的範例程式碼:
function Banners(props) { const [response, setResponse] = useState([]); const fetchData = async () => { const response = await axios.get(`${apiUrl}/assets/get`); setResponse(response); }; useEffect(() => { fetchData(); }, []); return ( <MainContent text={response.text} img1={props.img1 ? props.img1 : response.data.img1} img2={props.img2 ? props.img2 : response.data.img2} /> ); }