0

我是 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>
      );
    }

  }

4

2 回答 2

0

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

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) {
      
    }
  }
于 2021-06-10T15:01:38.313 回答
0

用于JSON.parse从 AsyncStorage 获取的值

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

于 2021-06-10T15:02:34.910 回答