API数据存入React State后无法立即读取,如何解决?
解决React中Shazam API数据存入State后无法立即更新的问题
问题场景
开发音乐Web应用时,调用Shazam API获取榜单数据并存入React State,试图在同一个函数内用State中的数据设置图片地址,结果第一次调用函数时图片无法加载,必须执行第二次才能成功。
原代码
获取数据的函数:
/* 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'/>
问题原因
React的setState是异步操作,调用setUsHopChart(response)后,usHopChart不会立刻更新为新的API返回数据。此时紧接着调用setChartImg(usHopChart[1]?.images?.coverart),拿到的是更新前的旧值(通常是初始的空值/undefined),导致第一次调用时图片地址设置失败。第二次调用函数时,usHopChart已经是第一次返回的有效数据,才能正确设置图片地址。
解决方案
方案1:直接使用API响应数据设置图片地址(推荐)
在API响应的回调中,直接用刚拿到的response数据设置chartImg,无需依赖usHopChart的更新:
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); // 直接使用API返回的response设置图片地址 setChartImg(response[1]?.images?.coverart); }) .catch(err => console.error(err)); }
方案2:用useEffect监听State变化
如果需要根据usHopChart的变化自动更新图片地址,可以使用useEffect钩子监听usHopChart的更新,在它变化时自动设置chartImg:
// 在组件内部添加useEffect钩子 import { useEffect } from 'react'; useEffect(() => { // 当usHopChart存在有效数据时,更新图片地址 if (usHopChart?.length > 1) { setChartImg(usHopChart[1]?.images?.coverart); } }, [usHopChart]); // 仅当usHopChart变化时执行 // 修改后的getUsChart函数仅负责更新榜单数据 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)); }
内容的提问来源于stack exchange,提问作者Tomiwa
相关产品推荐
相关产品推荐

