在 React Native 中使用异步存储计数器

问题描述

我是 React Native 的新手。 我想在 React Native Expo 中使用异步存储制作一个计数器。 异步存储适用于字符串值,但我需要使用整数值并且找不到创建它的示例。

如果您建议使用 sqlite 或者如果有不同的存储区域,我将不胜感激。


  storeData = async (counter) => {
    try {
      await AsyncStorage.setItem('',counter)
    } catch (e) {
      
    }
  }
  getData = async () => {
    try {
      const value = await AsyncStorage.getItem('counter')
      if(counter !== null) {

      }
    } catch(e) {
      
    }
  }

  render() {
      return(
        <SafeAreaView style={styles.container}>
          <imagebackground  style={styles.image}>
              <View style={{marginBottom: 250}}>
                    <Text style={styles.counter}>{counter}</Text>
              </View>
              <TouchableOpacity 
                style={styles.floatingButton1}
                onPress={this.onAddCounter}>
                <Text style={{fontSize:13,color:"white",fontWeight:"600"}}>Tap to Counter</Text>
              </TouchableOpacity>
             <TouchableOpacity 
              style={styles.resetButton1}
              onPress={this.onReset1}>
                <Icon name="undo" size={20} color="#900"/>
             </TouchableOpacity>
          </imagebackground>
        </SafeAreaView>
      );
    }

  }

解决方法

存储值时可以将整数转换为字符串:

number.toString()

并在检索值时将其转换为整数

parseInt(string)

基本上会变成

storeData = async (counter) => {
    try {
      await AsyncStorage.setItem('counter',counter.toString())
    } catch (e) {
      
    }
  }
  getData = async () => {
    try {
      const value = await AsyncStorage.getItem('counter')
      if(counter !== null) {
          value = parseInt(value)
      }
    } catch(e) {
      
    }
  }
,

使用 JSON.parse 获取从 AsyncStorage 获取的值

https://react-native-async-storage.github.io/async-storage/docs/usage/#reading-object-value