반응형
별도의 구성 요소에 가져오기 기능 삽입
다음 구성 요소에서 petchImages 기능을 꺼내 새 구성 요소 안에 넣으려고 한다.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
import UnsplashImage from './UnsplashImage';
const Collage = () => {
const [images, setImages] = useState([]);
const [loaded, setIsLoaded] = useState(false);
const fetchImages = (count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey =
'<API KEY>';
axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
setImages([...images, ...res.data]);
setIsLoaded(true);
});
};
useEffect(() => {
fetchImages();
}, []);
return (
<div className="image-grid">
{loaded
? images.map(image => (
<UnsplashImage
url={image.urls.regular}
key={image.id}
alt={image.description}
/>
))
: ''}
</div>
);
};
export default Collage;
이를 위해 api.js라는 새로운 컴포넌트를 만들어, 위의 컴포넌트에서 fetchImage 함수 전체를 제거하고 api.js에 다음과 같이 넣었다.
api.js
const fetchImages = (count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey =
'<API KEY>';
axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
setImages([...images, ...res.data]);
setIsLoaded(true);
});
};
export default fetchImages;
다음으로 나는 api.js에서 setIsLoaded(true)를 가져와서 다음과 같이 Collage 구성 요소 안에 붙여넣었다.
useEffect(() => {
fetchImages();
setIsLoaded(true);
}, []);
이제 petchImages를 Collage 구성 요소로 가져올 수 있다.
하지만 petchImages 함수 안에 있는 이 줄을 어떻게 해야 할지 모르겠어.이것은 Collage 컴포넌트로 가야 하지만 res.data는 Collage 컴포넌트 내부에 정의되어 있지 않다.
setImages([...images, ...res.data]);
어떻게 대처해야 할까?
그렇게 하는 데는 여러 가지 방법이 있지만, 당신 같은 경우에는.당신은 사용해야만 한다.
const fetchImages = (afterComplete, count = 10) => {
const apiRoot = 'https://api.unsplash.com';
const accessKey = '<API KEY>';
axios
.get(`${apiRoot}/photos/random?client_id=${accessKey}&count=${count}`)
.then(res => {
console.log(res);
afterComplete(res.data);
});
};
export default fetchImages;
콜라주 구성 요소:
const afterComplete = (resData) =>{
setImages([...images, ...resData]);
setIsLoaded(true);
}
useEffect(() => {
fetchImages(afterComplete);
}, []);
사용자 지정 후크(HORK와 같은 종류)를 만들면...나는 API 키가 없기 때문에 다른 API를 예로 들겠지만 아이디어는 같다.
사용자 지정 후크:
import { useState, useEffect } from 'react';
export const useFetch = url => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const fetchUser = async () => {
const response = await fetch(url);
const data = await response.json();
const [user] = data.results;
setData(user);
setLoading(false);
};
useEffect(() => {
fetchUser();
}, []);
return { data, loading };
};
구성 요소에서 이 제품을 사용하는 방법은 다음과 같다.
import { useFetch } from './api';
const App = () => {
const { data, loading } = useFetch('https://api.randomuser.me/');
return (
<div className="App">
{loading ? (
<div>Loading...</div>
) : (
<>
<div className="name">
{data.name.first} {data.name.last}
</div>
<img className="cropper" src={data.picture.large} alt="avatar" />
</>
)}
</div>
);
};
다음은 라이브 데모: https://codesandbox.io/s/3ymnlq59xm
참조URL: https://stackoverflow.com/questions/55445015/putting-fetch-function-in-a-separate-component
반응형
'programing' 카테고리의 다른 글
ReactRedex TypeScript 앱이 iPhone 6 iOS 12.0.1(공백색 화면인 경우)을 제외한 모든 곳에서 작동하는 이유는? (0) | 2022.03.31 |
---|---|
왜 Python은 제곱근에 대해 "잘못된" 대답을 하는가?파이썬 2의 정수분할이란? (0) | 2022.03.31 |
라우터 내부 다음('profile').각자가 오류를 발생시키기 전에 이를 파악하기 위해 도움이 필요함 (0) | 2022.03.31 |
v-data-table에 클릭 이벤트를 추가하는 방법 (0) | 2022.03.30 |
'Next' 속성이 'Observable<{}') 유형에 없음 (0) | 2022.03.30 |