使用相同属性在异步存储中多次保存值

时间:2018-12-07 08:03:11

标签: javascript reactjs react-native

我是新来的本地人。
通过将InputText的2个值放在“ text1”和“ text2”中,我能够在异步存储中保存2个TextInputs值。 现在,我正在尝试如果我按下(Next)按钮,然后再次使这2个InputText似乎再次获得2个值,并在相同的text1和text2属性内再次将这2个值保存在asyn存储中,而不擦除或重置以前保存的2个值。

// AddScreen.js

import React, { Component } from 'react';
import { AppRegistry, AsyncStorage, View, Text, Button, TextInput, StyleSheet, Image, TouchableHighlight, Linking } from 'react-native';
import styles from '../components/styles';
import { createStackNavigator } from 'react-navigation';
import History from '../components/History';

export default class AddScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            myKey: '',
            costKey: '',
            text1: '',
            text2: '',
        }
    }
    async getKey() {
        try {
            const value = await AsyncStorage.getItem('@MySuperStore:key');
            const key = await AsyncStorage.getItem('@MySuperStore:key');
            const key1 = await AsyncStorage.getItem('@MySuperStore:key1');
            const key2 = await AsyncStorage.getItem('@MySuperStore:key2');
            this.setState({
                myKey: key,
                costKey: key2
            });
        } catch (error) {
            console.log("Error retrieving data" + error);
        }
    }

    async saveKey(text1, text2) {
        key = text1 + text2;
        try {
            await AsyncStorage.setItem('@MySuperStore:key', key);
            await AsyncStorage.setItem('@MySuperStore:key1', text1);
            await AsyncStorage.setItem('@MySuperStore:key2', text2);
        } catch (error) {
            console.log("Error saving data" + error);
        }
    }

    async resetKey() {
        try {
            await AsyncStorage.removeItem('@MySuperStore:key');
            await AsyncStorage.removeItem('@MySuperStore:key2');
            const value = await AsyncStorage.getItem('@MySuperStore:key');
            const large = await AsyncStorage.getItem('@MySuperStore:key2')
            this.setState({
                myKey: value,
                costKey: large
            });
        } catch (error) {
            console.log("Error resetting data" + error);
        }
    }

    componentDidMount() {
        //this.getKey();
    }

    render() {
        const { navigate } = this.props.navigation;
        return (
            <View style={styles.MainContainer}>

                <TextInput
                    style={styles.formInput}
                    placeholder="Enter key you want to save!"
                    value={this.state.myKey}
                    onChangeText={(value) => this.setState({ text1: value })}
                />
                <TextInput
                    style={styles.formInput}
                    placeholder="Enter key you want to save!"
                    value={this.state.costKey}
                    onChangeText={(value) => this.setState({ text2: value })} />

                <Button
                    onPress={() => this.saveKey(this.state.text1, this.state.text2)}
                    title="Save key"
                />
                <Button
                    style={styles.formButton}
                    onPress={this.getKey.bind(this)}
                    title="Get Key"
                    color="#2196f3"
                    accessibilityLabel="Get Key"
                />
                <Button
                    style={styles.formButton}
                    onPress={this.resetKey.bind(this)}
                    title="Reset"
                    color="#f44336"
                    accessibilityLabel="Reset"
                />

                <Text style={styles.instructions}>
                    Stored key is = {this.state.myKey}
                </Text>
                <Text style={styles.instructions}>
                    Stored key is = {this.state.costKey}
                </Text>
                <Button
                    onPress={() => navigate('AddScreen', {
                        })}
                    title="Next"
                />
            </View>
        )
    }
}

我的意思是认为我的(AddScreen.js)组件是一个小盒子,其中在'text1'和'text2'中包含2个InputText值,并将该小盒子标记为大容器异步存储小盒子1.现在,如果我按(下一步)按钮,则新的新鲜小盒子会再次出现(AddScreen.js) 然后我再次将2个InputText值放入相同的'text1'和'text2'属性中,并通过标记该小盒子2将小盒子再次放置在较大的异步存储容器中。等等。 (下一个)按下。

请以我的示例为例,建议如何处理异步存储。

2 个答案:

答案 0 :(得分:0)

要求是:

  

在AsyncStorage中保存多个(n)值,需要按顺序提取。

最简单的方法是使用数组。您可以最初使用初始值创建一个数组。然后JSON.stringify将其保存到AsyncStorage中。然后,在提交下一个表单时,从AsyncStorage获取保存的数组,解析该数组,附加新值,然后将其放回AsyncStorage。

要保存数组:

const someArray = [1,2,3,4];
return AsyncStorage.setItem('somekey', JSON.stringify(someArray))
      .then(json => console.log('success!'))
      .catch(error => console.log('error!'));

要从AsyncStorage读取阵列,请执行以下操作:

return AsyncStorage.getItem('somekey')
  .then(req => JSON.parse(req))
  .then(json => console.log(json))
  .catch(error => console.log('error!'));

答案 1 :(得分:0)

您不能在AsyncStorage中存储具有相同键名的多个数据。 要实现此功能,请将数据存储在AsyncStorage中作为对象的字符串数组。

let inputKeyArray = []
let dataToBeStored = {
     '@MySuperStore:key': key,
     '@MySuperStore:key': text1,
     '@MySuperStore:key': text2      
}

AsyncStorage.getItem('inputKeyArray', (err, resp) => {       // Getting data from AsyncStorage
    let responseData = JSON.parse(resp)

        inputKeyArray = responseData || []
        inputKeyArray.push(dataToBeStored)
        AsyncStorage.setItem('inputKeyArray', JSON.stringify(inputKeyArray))  // Setting Your Data in AsyncStorage
            .then(res => console.log('success!'))
            .catch(error => console.log('error!'))

})