使用 react.js 连接到 API 后无法加载图像
Can't get image to load after connecting to an API using react.js
我已经创建了一个自定义获取组件,我只是想从名为“狗 API”的 API 获取要加载到页面上的图像。我错过了一些重要的事情吗?
App.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/
所以你 API 调用(根据 thedogapi.com 上的示例)需要在 header 中设置 API 键,如下所示:
axios.defaults.headers.common['x-api-key'] = "DEMO-API-KEY"
这修复了 404,但您的代码仍然无法正常工作,因为数据以 objects 的数组形式返回。所以你需要像这样映射它们:
{data.map((breed) => (<img src={breed?.url} />))}
我已经创建了一个演示沙箱 here
我已经创建了一个自定义获取组件,我只是想从名为“狗 API”的 API 获取要加载到页面上的图像。我错过了一些重要的事情吗?
App.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/
所以你 API 调用(根据 thedogapi.com 上的示例)需要在 header 中设置 API 键,如下所示:
axios.defaults.headers.common['x-api-key'] = "DEMO-API-KEY"
这修复了 404,但您的代码仍然无法正常工作,因为数据以 objects 的数组形式返回。所以你需要像这样映射它们:
{data.map((breed) => (<img src={breed?.url} />))}
我已经创建了一个演示沙箱 here