您需要在useEffect Hook中包裝異步API調(diào)用,并將數(shù)據(jù)存儲在狀態(tài)中,以便在渲染函數(shù)中使用該狀態(tài)。以下是一個沒有測試的示例代碼:
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} /> ); }