个性化阅读
专注于IT技术分析

React Native AsyncStorage持久化 – React Native实战教程

点击下载

上一章React Native实战教程请查看:React Native Geolocation地理定位

在本章中,我们将展示如何使用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
赞(4)
未经允许不得转载:srcmini » React Native AsyncStorage持久化 – React Native实战教程

评论 抢沙发

评论前必须登录!