[프로젝트-DediCats] Devlog-6

김대연·2020년 2월 12일
1

Project DediCats

목록 보기
7/16

FlatList 는 어플에서 뉴스피드 기능을 만들 때 유용한데, Infinite Scroll(무한 스크롤 로딩) 과 Pull Down Refresh(끌어서 새로고침) 기능을 구현할 수 있기 때문이다.

먼저 이 기능들의 구현은 해당 블로그 에서 참고하여 작성하였다.

또한 구현할 때 테스트를 위해 jsonplaceholder.com 에서 fake REST API 를 사용하였다.


먼저 스토어에 작성한 observable 변수들과 action 함수들이다.

// pagination 기능을 위해 페이지의 값을 할당한 변수
postPage = 1;

// 새로 고침을 확인하는 boolean
isRefreshingPost = false;

// 데이터를 요청해서 새로 갱신할지, 기존의 데이터에 추가할지 결정하는 함수
getPostList = async () => {
    // axios로 catPost들을 get해서 this.info.postList 업데이트
  try {
    // page 부분으 postPage로 지정해줘서 값이 더해지면 새로운 페이의 값을 응답으로 보낸다.
    const url = `https://jsonplaceholder.typicode.com/photos?_limit=6&_page=${this.postPage}`;
    // 요청을 비동기로 처리한다.
    const post = await Axios.get(url);
    // 만약 응답이 제대로 왔다면
    if (post) {
      // 그리고 새로 고침을 한다면
      if (this.isRefreshingPost) {
        // 응답으로 온 값을 새로 할당해준 후 boolean 을 다시 false로 변경해준다.
        this.info.postList = post.data;
        this.isRefreshingPost = false;
      // 새로 고침이 아니라면 -> 로딩을 하는 것이라면
      } else {
        // 기존에 존재하는 데이터에 concat으로 병합해준다.
        this.info.postList = this.info.postList.concat(post.data);
      }
    }
  } catch (error) {
    console.error(error);
  }
};

// 페이지의 state를 +1 한 후 새 페이지를 받아오도록 getPostList를 실행한다.
_handleLoadMorePosts = () => {
  this.postPage += 1;
  this.getPostList();
}

// isRefreshingPost를 true로 변경하여 조건을 성립시키고, postPage를 다시 1로 리셋시켜 처음 데이터 값을 응답으로 받는다.
_handleRefresh = () => {
  this.isRefreshingPost = true;
  this.postPage = 1;
  this.getPostList();

그리고 mobX로 스토어한 observable 들과 action 들을 inject 한 실제 코드이다.

  // 처음 렌더되고 componentDidMount에서 페이지 1의 데이터들을 받아온다.
  componentDidMount() {
    this.props.getPostList();
  }

  // 스크린에 render 될 item 에 따른 컴포넌트이다.
  _renderItem = ({ item }) => (
    <CatPost item={item} setCatPost={this.props.setCatPost} />
  );

  // (Infinite Scroll) 렌더가 일어날 때 Footer 에서 ActivityIndicator를 이용하여 로딩 중을 표현한다.
  renderFooter = () => (
    <View style={styles.loader}>
      <ActivityIndicator size="large" />
    </View>
  );

  render() {
    return (
      <View style={styles.container}>
        <SafeAreaView style={styles.radiusView}>
          <FlatList
            data={this.props.postList}
            renderItem={this._renderItem}
            keyExtractor={(item, index) => `${item.id}`}
            showsVerticalScrollIndicator={false}
            onEndReached={this.props._handleLoadMorePosts}
            onEndReachedThreshold={1}
            ListFooterComponent={this.renderFooter}
            refreshing={this.props.isRefreshingPost}
            onRefresh={this.props._handleRefresh}
          />
        </SafeAreaView>
        <CatPostInput />
      </View>
    );
  }
}

작성한 코드대로라면 이렇게 실행된다.

0개의 댓글