All Articles

[React Native] 4장 모바일 컴포넌트

빠른 모바일 앱 개발을 위한 React Native 2/E 를 보면서 하고 있는데 코드 오류가 좀 있다.

  1. chapter4의 책 목록이 불러와지지 않는다. nytimes api key가 만료된 것인지 —> 다음 책 검색으로 바꿨다.
  2. 책 목록이 보이지 않는다 —> .bookItemflex: 1를 추가해야 가로로 채워짐
  3. 간단한 오타 몇 개

FlatList

<FlatList> 컴포넌트는 데이터 목록을 짜임새 있게 보여줘야 할 때 손쉽게 적용할 수 있다. 스크롤, 터치 인터랙션을 다루는 것도 가능하고 렌더링 스피드와 메모리 사용량을 줄이기 위해 성능 최적화 기술이 많이 적용되어 있다.

FlatList, SectionList를 사용할 때, react.js와 가장 다른 점은 map함수를 사용하지 않는다는 것이다. FlatList data와 renderItem으로 알아서 map함수를 돌리고 render하는 것처럼 되어있는데, 그래서 인지 data 배열에 key 프로퍼티가 꼭 있어야 한다.

typescript를 추가해봤다.

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
} from 'react-native';
import BookItem from './Components/BookItem';
import NYT from './NYT';

type AppState = {
  data: Array<any>;
}

type bookType = {
  key: string;
  title: string;
  thumbnail: string;
  authors: Array<string>;
}

type itemType = {
  item: bookType
}

class App extends Component<any, AppState> {

  state = {
    data: []
  };

  componentDidMount() {
    NYT.fetchBooks().then(books => {
      this.setState({
        data: this._addKeysToBooks(books)
      })
    })
  }

  _renderItem = ({ item }: itemType) => (
    <BookItem
      coverURL={item.thumbnail}
      title={item.key}
      author={item.authors[0]}
    >
      {item.key}
    </BookItem>
  );

  _addKeysToBooks = (books: []) => books.map((book: bookType) => ({ key: book.title+book.authors[0], ...book }));

  render() {
    return (
      <View style={styles.container}>
        <FlatList
          data={this.state.data}
          renderItem={this._renderItem}
        />
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#ffffff',
    padding: 10,
    paddingTop: 30
  }
});

export default App;

SectionList

SectionList는 FlatList보다 조금 더 복잡한 ui를 구현하고 싶을 때 사용한다. 당장 FlatList와의 큰 차이점은 잘 모르겠다.

<SectionList>의 sections의 속성은 배열이 아니라 객체인데, data와 title 속성이 들어가야 한다.

공부만 하는 입장에선 두 개를 꼭 나눴어야 했던 이유를 딱히 모르겠다.. docs를 자세히 봐야겠다. wip..