React-native-asyncstorage

提供:Dev Guides
移動先:案内検索

React Native-AsyncStorage

この章では、 AsyncStorage を使用してデータを永続化する方法を示します。

ステップ1:プレゼンテーション

このステップでは、 App.js ファイルを作成します。

import React from 'react'
import AsyncStorageExample from './async_storage_example.js'

const App = () => {
   return (
      <AsyncStorageExample/>
   )
}
export default App

ステップ2:ロジック

初期状態の*名前*は空の文字列です。 コンポーネントがマウントされたら、永続ストレージから更新します。

*setName* は入力フィールドからテキストを取得し、 *AsyncStorage* を使用して保存し、状態を更新します。

async_storage_example.js

import React, { Component } from 'react'
import { StatusBar } from 'react-native'
import { AsyncStorage, Text, View, TextInput, StyleSheet } from 'react-native'

class AsyncStorageExample extends Component {
   state = {
      'name': ''
   }
   componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({ 'name': value }))

   setName = (value) => {
      AsyncStorage.setItem('name', value);
      this.setState({ 'name': value });
   }
   render() {
      return (
         <View style = {styles.container}>
            <TextInput style = {styles.textInput} autoCapitalize = 'none'
            onChangeText = {this.setName}/>
            <Text>
               {this.state.name}
            </Text>
         </View>
      )
   }
}
export default AsyncStorageExample

const styles = StyleSheet.create ({
   container: {
      flex: 1,
      alignItems: 'center',
      marginTop: 50
   },
   textInput: {
      margin: 5,
      height: 100,
      borderWidth: 1,
      backgroundColor: '#7685ed'
   }
})

アプリを実行すると、入力フィールドに入力してテキストを更新できます。

React Native AsyncStorage