[英]I'm fetching a problem when I'm trying to fetch data from an API by using useEffect in react
[英]I have a problem with fetching data with useEffect
這是我的代碼。
import React from 'react'
import { useEffect, useState } from 'react';
import './style.css'
function App(){
let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
"method": "GET",
"headers": {
"x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
"x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
}
})
useEffect(()=>{
(async function(){
let data = await fetch(api).then(res=>res.json());
console.log(data);
})();
},[api]);
return(
<div>Test</div>
);
};
export default App;
這是我得到的錯誤。
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
它適用於其他簡單的 api 調用,如“https://www.breakbadapi.com/api/”,但它不適用於我正在使用的這個 api,我不知道為什么。
let api = ("https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
"method": "GET",
"headers": {
"x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
"x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
}
})
您使用的是逗號運算符,因此api
將僅包含 url 之后出現的 object。
將其存儲為 object 或數組:
const api = ["https://free-to-play-games-database.p.rapidapi.com/api/game?id=452", {
"method": "GET",
"headers": {
"x-rapidapi-host": "free-to-play-games-database.p.rapidapi.com",
"x-rapidapi-key": "f65083b32emshf3a0f94016a0bb1p159106jsn48481cc9c6ca"
}
}]
function App() {
useEffect(() => {
(async function () {
const [url, options] = api;
let data = await fetch(url, options).then(res => res.json());
console.log(data);
})();
}, []); // this can be empty as api is outside and doesn't change
return (
<div>Test</div>
);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.