React Native - 持久化存儲(AsyncStorage)的使用詳解



1,AsyncStorage介紹

  • AsyncStorage 是一個簡單的、異步的、持久化的 Key-Value 存儲系統,它對於 App 來說是全局性的。它用來代替 LocalStorage
  • 由於它的操作是全局的,官方建議我們最好針對 AsyncStorage 進行一下抽象的封裝再使用,而且不是直接拿 AsyncStorage 進行使用。
  • AsyncStorage 存儲的位置根據系統的不同而有所差異。iOS 中的存儲類似於 NSUserDefault,通過 plist 文件存放在設備中。Android 中會存儲在 RocksDB 或者 SQLite 中,取決於你使用哪個。

2,相關方法

(1)根據鍵來獲取值,獲取的結果會放在回調函數中。
1
static getItem(key: string, callback:(error, result))

(2)根據鍵來設置值。
1
static setItem(key: string, value: string, callback:(error))

(3)根據鍵來移除項。
1
static removeItem(key: string, callback:(error))

(4)合併現有值和輸入值。
1
static mergeItem(key: string, value: string, callback:(error))

(5)清除所有的項目
1
static clear(callback:(error))

(6)獲取所有的鍵
1
static getAllKeys(callback:(error, keys))

(7)清除所有進行中的查詢操作。
1
static flushGetRequests()

(8)獲取多項,其中 keys 是字符串數組,比如:['k1', 'k2']
1
static multiGet(keys, callback:(errors, result))

(9)設置多項,其中 keyValuePairs 是字符串的二維數組,比如:[['k1', 'val1'], ['k2', 'val2']]
1
static multiSet(keyValuePairs, callback:(errors))

(10)刪除多項,其中 keys 是字符串數組,比如:['k1', 'k2']
1
static multiRemove(keys, callback:(errors))

(11)多個鍵值合併,其中 keyValuePairs 是字符串的二維數組,比如:[['k1', 'val1'], ['k2', 'val2']]
1
static multiMerge(keyValuePairs, callback:(errors))

二、使用樣例

1,效果圖

(1)在文本輸入框中輸入姓名、電話後,點擊“保存”按鈕即可通過 AsyncStorage 存儲起來。
(2)退出程序後再次打開,程序又會自動加載之前保存的信息。
(3)點擊“清除”按鈕則將本地保存的數據全部清除。
原文:React Native - 持久化存儲(AsyncStorage)的使用詳解原文:React Native - 持久化存儲(AsyncStorage)的使用詳解

2,樣例代碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TextInput,
  AsyncStorage
} from 'react-native';
 
//用戶信息填寫組件
class UserInfo extends Component {
  //構造函數
  constructor(props) {
    super(props);
    this.state = {name: '', phone: ''};
  }
 
  //頁面的組件渲染完畢(render)之後執行
  componentDidMount(){
    var _that = this;
 
    //需要查詢的鍵值
    var keys = ["name","phone"];
    //根據鍵數組查詢保存的鍵值對
    AsyncStorage.multiGet(keys, function(errs, result){
      //如果發生錯誤,這裏直接返回(return)防止進入下面的邏輯
      if(errs){
        return;
      }
 
      //得到的結果是二維數組(result[i][0]表示我們存儲的鍵,result[i][1]表示我們存儲的值)
      _that.setState({
        name: (result[0][1]!=null)?result[0][1]:'',
        phone: (result[1][1]!=null)?result[1][1]:''
      });
    });
  }
 
  //組件渲染
  render() {
    return (
      <View style={styles.flex}>
          <View style={styles.row}>
            <View style={styles.head}>
              <Text style={styles.label}>姓名</Text>
            </View>
            <View style={styles.flex}>
              <TextInput style={styles.input}
                value={this.state.name}
                onChangeText={(name) => this.setState({name})}/>
            </View>
          </View>
          <View style={styles.row}>
            <View style={styles.head}>
              <Text style={styles.label}>電話</Text>
            </View>
            <View style={styles.flex}>
              <TextInput style={styles.input}
                value={this.state.phone}
                onChangeText={(phone) => this.setState({phone})}/>
            </View>
          </View>
          <View style={styles.row}>
              <Text style={styles.btn} onPress={this.save.bind(this)}>保存</Text>
              <Text style={styles.btn} onPress={this.clear.bind(this)}>清除</Text>
          </View>
      </View>
    );
  }
 
  //保存數據
  save() {
    //設置多項
    var keyValuePairs = [['name', this.state.name], ['phone', this.state.phone]]
    AsyncStorage.multiSet(keyValuePairs, function(errs){
      if(errs){
        //TODO:存儲出錯
        return;
      }
      alert('數據保存成功!');
    });
  }
 
  //清除數據
  clear() {
    var _that = this;
    AsyncStorage.clear(function(err){
      if(!err){
        _that.setState({
          name: "",
          phone: ""
        });
        alert('存儲的數據已清除完畢!');
      }
    });
  }
}
 
//默認應用的容器組件
class App extends Component {
   render() {
      return (
        <View style={[styles.flex, styles.topStatus]}>
         <UserInfo></UserInfo>
        </View>
      );
   }
 }
 
//樣式定義
const styles = StyleSheet.create({
  flex:{
    flex: 1,
  },
  topStatus:{
    marginTop:25,
  },
  row:{
    flexDirection:'row',
    height:45,
    marginBottom:10
  },
  head:{
    width:70,
    marginLeft:5,
    backgroundColor:'#23BEFF',
    height:45,
    justifyContent:'center',
    alignItems: 'center'
  },
  label:{
    color:'#fff',
    fontSize:15,
    fontWeight:'bold'
  },
  input:{
    height:45,
    borderWidth:1,
    marginRight: 5,
    paddingLeft: 10,
    borderColor: '#ccc'
  },
  btn:{
    flex:1,
    backgroundColor:'#FF7200',
    height:45,
    textAlign:'center',
    color:'#fff',
    marginLeft:5,
    marginRight:5,
    lineHeight:45,
    fontSize:15,
  },
});
 
AppRegistry.registerComponent('HelloWorld', () => App);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章