我想獲取一個影像 url用作src 標記的值
<img
src={getAircraftImage(foundFlight.aircraft.reg)}
alt="Aircraft"
className="rounded-md w-24 h-12"
/>
function getAircraftImage(reg: string | undefined): string {
let imageUrl;
const options = {
method: "GET",
url: `https://aerodatabox.p.rapidapi.com/aircrafts/reg/${reg}/image/beta`,
headers: {
"X-RapidAPI-Key": "6445ce28c1msh4b2afb9dc1a38bbp17a68bjsn97511bcb4bbf",
"X-RapidAPI-Host": "aerodatabox.p.rapidapi.com",
},
};
axios
.request(options)
.then(function (response) {
imageUrl = response.data.url;
})
.catch(function (error) {
console.error(error);
});
return imageUrl;
}
問題Api 沒那么快。當我加載影像時,只顯示 alt 標簽。我在多個網站上看到了一種在發出請求時顯示后備影像的方法,然后在之后顯示正確的影像,但我不知道如何實作它。我如何做到這一點?
uj5u.com熱心網友回復:
正如評論中所說:只需使用鉤子。useEffect
正確執行請求,useState
存盤結果并有條件地呈現。您可能希望在需要向外部 API 發出請求的任何場景中使用此鉤子組合。作為代碼示例,對于一個簡單的組件:
import React, { useEffect, useState} from 'react';
import axios from 'axios';
const MyComponent = () => {
// create state of loading, but also state for data
const [loading, setLoading] = useState(true);
const [data, setData] = useState([])
// useEffect to execute request
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
// gets response and saves data into 'data' state
const {data: response} = await axios.get('/stuff/to/fetch');
setData(response);
} catch (error) {
console.error(error.message);
}
setLoading(false);
}
fetchData();
}, []);
// conditional rendering if already loaded
return (
<div>
{loading && <div>Loading</div>}
{!loading && (
<div>
<h2>Doing stuff with data</h2>
{data.map(item => (<span>{item.name}</span>))}
</div>
)}
</div>
)
}
export default MyComponent;
來源:https ://dev.to/darkmavis1980/fetching-data-with-react-hooks-and-axios-114h
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/527572.html
標籤:反应打字稿axios
上一篇:從位于url-#${id}的@Patch@Delete回傳變數。NestJS課程第12課
下一篇:選擇一個屬性的通用函式