sugiken のメモ帳

知ったことを書いていく

【Rep】授業データを受け取って、リスト表示するまで

Repアプリ開発についてです。

前回、こちらの記事で「もっとゆっくり進もう」ということにしました。

kentear.hatenablog.com

というわけで、本当にすこ〜〜しづつ進めてアプリ開発をしています。
まだcomponentに分けてもいないですし、関数で整理とか意識してないです。

できるようになったこと

  • 文字を入力する
  • 入力した文字を受け取る
  • RepのAPI URLを叩く
  • API URLに入力した文字を入れて、授業名検索をする
  • 受け取った授業データの授業名を表示する

ようやくReactにおけるStateの意味がわかってきました。
setStateで値を変えるだけで、そのstateを使っている部分が書き換わるなんて!!

実装コード

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TextInput,
  Button,
  Alert,
  View,
  FlatList,
  SectionList
} from 'react-native';

export default class Rep extends Component {
  constructor(props) {
    super(props)
    this.state = {
      text: 'Business',
      lessons: []
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <TextInput
          style={{height: 40, width: 300, borderColor: 'gray', borderWidth: 1}}
          onChangeText={(text) => this.setState({text})}
          value={this.state.text}
        />
        <Button
          onPress={(text) => this.getLessonSearch(this.state.text)}
          title="Send"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
        <FlatList
        data={
          this.state.lessons
        }
        renderItem={({item}) => <Text>{item.lesson_name}</Text>}
        />
      </View>
    );
  }
  getLessonSearch(text) {
    return fetch('RepのAPI URL')
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({
          lessons: responseJson
        });
        return responseJson;
      })
      .catch((error) => {
        console.error(error);
      });
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

AppRegistry.registerComponent('Rep', () => Rep);

画面挙動

f:id:kentear:20171007002205g:plain

結構いい感じに動いています!!
プログラミングを始めたときの感動が再燃しています🔥

ここまでやった所感

  • 公式ドキュメントのSimple Exampleがわかりやすい
  • そのSimple Exampleを見れば、今回のような最低限の機能はできそう
  • Javascriptの勉強はしないといけない

最後のは当然過ぎますが、さすがにコピペで最後までやる気はないです。
ProgateJSの本をを使って勉強しようと思います。