我創建了一個自定義獲取組件,我只是想從一個名為“狗 API”的 API 獲取要在頁面上加載的影像。我錯過了什么重要的事情嗎?
應用程式.js
import './App.css';
import './Dog.js';
import useFetch from './useFetch';
function DogApp() {
const API_KEY = "";
const { data, loading, error } = useFetch(`https://api.thedogapi.com/v1/images/search/API_KEY=${API_KEY}`);
if (loading) return <h1>Loading the dogs!</h1>
if (error)console.log(error);
return (
<div className="DogApp">
<img src={data?.url}></img>
</div>
);
}
export default DogApp;
UseFetch.js(獲取資料的鉤子)
import { useEffect, useState } from 'react';
import axios from "axios";
function useFetch(url) {
const [data, setData] = useState(null); //initialize as null depending on what data is
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
axios //make request, if successful it sets data, if not, seterror state
.get(url)
.then((response) => {
setData(response.data);
}).catch((err) => {
setError(err)
}).finally(() => {
setLoading(false);
});
}, [url]);
return {data, loading, error};
}
export default useFetch;
我正在嘗試從以下位置檢索資料的 API URL:https ://api.thedogapi.com/v1/images/search/
uj5u.com熱心網友回復:
因此,您的 API 呼叫(根據 thedogapi.com 上的示例)需要在標頭中設定 API 密鑰,如下所示:
axios.defaults.headers.common['x-api-key'] = "DEMO-API-KEY"
這修復了 404,但您的代碼仍然無法作業,因為資料作為物件陣列回傳。所以你需要像這樣映射它們:
{data.map((breed) => (<img src={breed?.url} />))}
我在這里創建了一個演示沙箱
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/431579.html
標籤:javascript 反应 api 拿来
