React Native - 持久化存储(AsyncStorage)的使用详解 (值得学习的网站)

原文链接:http://www.hangge.com/blog/cache/detail_1567.html

一,基本概念

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);


原文出自:www.hangge.com  转载请保留原文链接:http://www.hangge.com/blog/cache/detail_1567.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用 `react-native-svg` 和 `react-native-svg-transformer` 加载本地 SVG 图像,你可以按照以下步骤进行操作: 1. 首先,确保你已经在项目中安装了 `react-native-svg` 和 `react-native-svg-transformer` 依赖。你可以通过运行以下命令来安装它们: ``` npm install react-native-svg react-native-svg-transformer ``` 2. 在项目的根目录下创建一个名为 `metro.config.js` 的文件(如果已存在,请跳过此步骤)。 3. 在 `metro.config.js` 文件中添加以下内容: ```javascript module.exports = { transformer: { assetPlugins: ['react-native-svg-transformer'], }, }; ``` 4. 接下来,在你的组件中,使用 `react-native-svg` 中的 `<SvgUri>` 组件来加载本地 SVG 图像。首先,确保你的 SVG 图像位于项目的 `assets` 文件夹中。 ```javascript import React from 'react'; import { View } from 'react-native'; import SvgUri from 'react-native-svg-uri'; const MyComponent = () => { return ( <View> <SvgUri width={200} height={200} source={require('./assets/myImage.svg')} /> </View> ); }; export default MyComponent; ``` 在上面的示例中,我们使用 `require` 方法加载位于 `assets` 文件夹中的 `myImage.svg` 图像,并将其作为 `source` 属性传递给 `<SvgUri>` 组件。你可以根据自己的需要调整宽度和高度。 5. 确保你在重新启动 Metro Bundler 之前完成了以上步骤。你可以通过运行以下命令重新启动 Metro Bundler: ``` npx react-native start --reset-cache ``` 这样,你就可以使用 `react-native-svg` 和 `react-native-svg-transformer` 成功加载和显示本地 SVG 图像了。 希望对你有所帮助!如有任何疑问,请随时提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值