1. 참고링크
: https://thewebdev.info/2022/02/19/how-to-implement-pull-to-refresh-flatlist-with-react-native/
How to implement pull to refresh FlatList with React Native? - The Web Dev
Spread the love Related Posts How to fix the React Native FlatList last item not visible issue?Sometimes, we want to fix the React Native FlatList last item not visible issue. In… How to hide the scrollbar in a FlatList with React Native in Android?Somet
thewebdev.info
ㄱ. 해당 링크의 코드스니펫 설명
: 카드 컴포넌트를 사용한 방식으로,
=> Flatlist에 관한 설정을 선언하고 (배열 수 200, card 컴포넌트를 map함수로 반복하는 등)
=> props로 들어가 Item변수에 대해 선언 (나중에 renderitem의 item에 사용할 title을 뽑아내기 위한 선언)
=> sleep로 타임아웃 시간 반응 설정 (시간 값은 onRefresh함수에서 비동기 선언을 통해 설정할 것임)
=> useState 설정 (여기선 isFetching이라 이룸설정함)
=> rederItem이라는 Flatlist의 option값을 선언. 대입될 값은 item으로 선언.( 아까 선언한 Item과 다름 )
여기에 아까 선언한 Item이라는 함수 안의 title이 들어가게 된다는 것
=> onRefresh 함수 선언. Async를 이용한 비동기 선언.
=> return으로 렌더링 선언
2. 사용준비 (기존 사용하던 Flatlist가 있다는 전제 하에 사용)
: 아래의 코드들을 import 해준다.
import * as React from 'react';
import { FlatList, Text, View } from 'react-native';
import Constants from 'expo-constants';
3. 적용방법
ㄱ. useState를 선언해준다.
export default function App() {
const [isFetching, setIsFetching] = React.useState(false);
ㄴ. 비동기로 데이터를 받아올 수 있게 onRefresh함수를 선언해준다.
const onRefresh = async () => {
setIsFetching(true);
await sleep(2000);
setIsFetching(false);
};
ㄷ. await에 들어갈 sleep에 대한 선언을 해준다.
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
ㄹ. return문의 Flatlist에 onRefresh와 refreshing option을 넣어준다.
return (
<View>
<FlatList
data={flatListItems}
onRefresh={onRefresh}
refreshing={isFetching}
renderItem={renderItem}
keyExtractor={(item) => item.id}
/>
</View>
);
4. 기타 참고사항 : 3번 항목의 'ㄹ'항목에 대한 추가설명
ㄱ. data에 들어갈 value값 flatListItems는 아래와 같이 따로 선언해줘도 되고, 기존의 데이터 값을 넣어줘도된다.
아래 코드는 map함수를 이용해 반복함수를 돌린 경우이다.
필자의 경우, useState를 활용한 getter변수값을 넣어뒀다.(외부 서버 연동을 위해)
const flatListItems = Array(200)
.fill()
.map((_, i) => ({ title: i, id: i }));
ㄴ. renderItem은 FlatList를 사용할 때 기본적으로 사용하는 렌더링 함수이다.
본인의 취향에 따라 태그를 넣거나 내부함수를 만들어도 된다.
여기선 미리 함수를 선언해두고 사용했다.
const renderItem = ({ item }) => <Item title={item.title} />;
ㄷ. keyExtractor 또한 FlatList를 사용할 때 기본적으로 사용하는 반복 함수용 option이다.
여기선 item이라는 변수에 대해 id를 활용한 반복함수를 돌리고 있기 때문에 'ㄱ'에서와 같이 flatListItems를 선언하고,
거기서 받아오는 것이다.
'React-native > 정리' 카테고리의 다른 글
| realtime database 찜하기 구현 (0) | 2022.06.09 |
|---|---|
| VirtualizedList 사용하기 (진행중) (0) | 2022.06.07 |
| [개정된 링크 참고] Playlist 만들기 (=Likepage) (0) | 2022.05.29 |
| realtime database 활용하기 (0) | 2022.05.27 |
| Loading화면 구현 (2) (0) | 2022.05.25 |