我正在使用react.js
async function Banners(props) {
const response = await axios.get(`${apiUrl}/assets/get`);
return (
<MainContent
text={response.text}
img1={props.img1 ? props.img1 : response.data.img1}
img2={props.img2 ? props.img2 : response.data.img2}
/>
);
}
当有"async"时才会出现错误
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您需要在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} /> ); }