使用 React 時,當我嘗試從 API 獲取數據時,我不斷收到 SyntaxError:JSON.parse 。在使用不同的 API 時,我能夠很好地獲取數據。
我在這裡做錯了什麼?說到 API,我是一個完全的新手,所以如果這是一個愚蠢的問題,請不要挖苦我:D
const API_URL = 'www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata';
const getMealRequest = async()=>{
const response = await fetch(API_URL)
const data = await response.json()
console.log(data)
}
useEffect(()=>{
getMealRequest()
},[])
您的 API 調用存在與此問題無關的錯誤。在失敗的情況下,您沒有try/cath
使用getMealRequest
so實現塊,這response
不是要解析的有效對象,並且您會收到上述錯誤。
要解決它:
const getMealRequest = async () => {
try {
const response = await fetch('https://www.themealdb.com/api/json/v1/1/search.php?s=Arrabiata'
)
const data = await response.json()
console.log(data)
} catch (error) {
console.log(error)
}
}
現在檢查您的控制台,看看您的 API 調用有什麼問題。此外,您可以檢查網絡選項卡以獲取有關調用的請求和響應的更多詳細信息API_URL
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句