我正在開發音樂網路應用程式的界面,因此我從 API 獲取資料并存盤在狀態中,全部由一個函式執行,以顯示在界面上。代碼如下:
/* function fetching the data*/
function getUsChart() {
const options = {
method: 'GET',
headers: {
'X-RapidAPI-Key': '036795ec2amsh8c2b98ef8a502acp146724jsn6f3538b26522',
'X-RapidAPI-Host': 'shazam-core.p.rapidapi.com'
}
};
fetch('https://shazam-core.p.rapidapi.com/v1/charts/genre-country?country_code=US&genre_code=HIP_HOP_RAP', options)
.then(response => response.json())
.then(response => setUsHopChart(response))
.catch(err => console.error(err));
/*I stored it in state here*/
setChartImg(usHopChart[1]?.images?.coverart)
}
/*I displayed it here*/
<img src={chartImg} className='chart-img rounded-3xl' alt='chart-image'/>
問題:
函式執行后,資料被獲取但沒有立即存盤在狀態中,直到第二次執行。因此導致:

請問我該怎么辦?
uj5u.com熱心網友回復:
我認為您需要將 setChartImg 移到里面
fetch('https://shazam-core.p.rapidapi.com/v1/charts/genre-country?country_code=US&genre_code=HIP_HOP_RAP', options)
.then(response => response.json())
.then(response => {
setUsHopChart(response)
setChartImg(response[1]?.images?.coverart)
})
.catch(err => console.error(err));
/*I stored it in state here*/
uj5u.com熱心網友回復:
我認為問題是在獲取程序完成之前呈現了 jsx。因此,最好的方法是創建一個布爾加載狀態并將其初始化為 true,當它的值為 true 時,創建一個微調器或 smth,并在 promise 回傳值時將其設為 false。
對于快速解決方案,也許您可??以執行以下操作:
{chartImg && <img src={chartImg} className='chart-img rounded-3xl' alt='chart-image'/>}
所以它的作用是在定義 chartImg 時(當你在 promise 解決后給它一個值時)它將呈現 jsx 元素,這是你的問題。
uj5u.com熱心網友回復:
我認為您想更快地獲取資料并將其存盤在狀態中。有辦法做到這一點。我給你舉個例子
const commentsPromise = fetch('/get-comments');
const Comments = () => {
useEffect(() => {
const dataFetch = async () => {
// just await the variable here
const data = await (await commentsPromise).json();
setState(data);
};
dataFetch();
}, [url]);
}
在這個例子中,我們的 fetch 呼叫基本上“轉義”了所有 React 生命周期,并且會在頁面上加載 javascript 后立即觸發,然后呼叫任何 useEffect anywere。
甚至在呼叫回圈 App 組件中的第一個請求之前。它將被觸發,javascript 將繼續處理其他事情,資料將靜靜地坐在那里,直到有人真正解決它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/528148.html
上一篇:如何延遲curl請求
