如何在连接到第三方后通过多张图片进行映射 api
how to map through multiple images, after connecting to a third party api
我已成功连接到 api,其中有 returns 条狗的图像。但是,我坚持如何在不重复代码的情况下映射多个图像。我基本上想显示一个带有(比方说 9)张图片的网格,所有图片都来自 api.
目前,它显示一张图像,其下方映射有一个 json 对象。
App.js
import './App.css';
import './Dog.js';
import FetchAPI from './FetchAPI';
function DogApp() {
return (
<div className="DogApp">
<FetchAPI />
</div>
);
}
export default DogApp;
FetchAPI.js
import React, { useState, useEffect } from 'react'
const FetchAPI = () => {
const [data, setData] = useState([]);
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
useEffect(() => { //call data when pagee refreshes/initially loads
apiGet();
}, []);
return (
<div>
{data.map((item) => (
<img src={item.url}></img>
))}
My API
<button onClick={apiGet}>Fetch API</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
<br />
</div>
)
}
export default FetchAPI;
如果您的 API returns 一次只有一张图片,并且您希望单击按钮时有更多图片,那么您应该将新图片附加到数组中,例如:
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData([...data,json]); // if json is single object
// setData([...data,...json]); // if json is array of one object then you should use this line
});
};
我已成功连接到 api,其中有 returns 条狗的图像。但是,我坚持如何在不重复代码的情况下映射多个图像。我基本上想显示一个带有(比方说 9)张图片的网格,所有图片都来自 api.
目前,它显示一张图像,其下方映射有一个 json 对象。
App.js
import './App.css';
import './Dog.js';
import FetchAPI from './FetchAPI';
function DogApp() {
return (
<div className="DogApp">
<FetchAPI />
</div>
);
}
export default DogApp;
FetchAPI.js
import React, { useState, useEffect } from 'react'
const FetchAPI = () => {
const [data, setData] = useState([]);
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData(json);
});
};
useEffect(() => { //call data when pagee refreshes/initially loads
apiGet();
}, []);
return (
<div>
{data.map((item) => (
<img src={item.url}></img>
))}
My API
<button onClick={apiGet}>Fetch API</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
<br />
</div>
)
}
export default FetchAPI;
如果您的 API returns 一次只有一张图片,并且您希望单击按钮时有更多图片,那么您应该将新图片附加到数组中,例如:
const apiGet = () => {
const API_KEY = "";
fetch(`https://api.thedogapi.com/v1/images/search?API_KEY=${API_KEY}`)
.then((response) => response.json())
.then((json) => {
console.log(json);
setData([...data,json]); // if json is single object
// setData([...data,...json]); // if json is array of one object then you should use this line
});
};