首页 > 解决方案 > react native:如何使用 AsyncStorage 存储完整状态及其所有道具

问题描述

我有Reminder Component一个简单的表单,其中包含一个TextInputfromreact-native和一个DatePickerfromnative-base以及一个submit用于存储点击时的值。

我正在尝试实现AyncStorage在本地存储这些值,然后在另一个屏幕上显示它们。但我无法这样做,因为我收到错误“未定义值”。

无论博客文章和 tuts 是什么,这个人都只存储一个单一的财产。我想存储完整的状态,即输入字段和保存按钮的点击日期。

这是我的ReminderComponent

import React, { Component } from 'react';
import { View,StyleSheet, AsyncStorage, TextInput } from 'react-native';
import {
    Form,
    Button, Icon,
    DatePicker, Text
} from 'native-base';
import PropTypes from 'prop-types';
class Reminder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            input: '',
            chosenDate: new Date(),
        };
        this.setDate = this.setDate.bind(this);
        this.handleChangeInput = this.handleChangeInput.bind(this);
        this.saveData = this.saveData.bind(this);
    }

    setDate(newDate) {
        this.setState({
            chosenDate: newDate
        });
    }

    handleChangeInput = (text) =>  {
        this.setState({input:text});
    }

    //On application loads, this will get the already saved data and set 
    //the state true when it's true.
    componentDidMount() {
        AsyncStorage.getItem("key").then((value) => {
            this.setState({'key':value});
        });
    }

    //save the input
    saveData(value) {
        console.log('value', value);
        AsyncStorage.setItem("key", value);
        this.setState({'key':value});
    }
    render() { 
      const {input} = this.state;
        return ( 
            <View>
                <Form style={styles.formContainer}>
                    <View style={styles.formView}>

                            < TextInput
                            placeholder = "Set your reminder"
                            onChangeText={this.handleChangeInput}
                            value={this.state.input}
                            />

                        <DatePicker
                            defaultDate={new Date()}
                            minimumDate={new Date(2018, 1, 1)}
                            maximumDate={new Date(2019, 12, 31)}
                            locale={"en"}
                            timeZoneOffsetInMinutes={undefined}
                            modalTransparent={false}
                            animationType={"fade"}
                            androidMode={"default"}
                            placeHolderText="Select date"
                            textStyle={{ color: "green" }}
                            placeHolderTextStyle={{ color: "#d3d3d3" }}
                            onDateChange={this.setDate}
                        />
                        <Text style={styles.datePicker}>
                            {this.state.chosenDate.toString().substr(4, 12)}
                        </Text>
                    </View>
                    <View style={styles.footer}>
                        <Button block success style={styles.saveBtn} 
                        onPress={ () => 
                            {this.saveData()
                            console.log('save data', value);}
                        } 
                           >
                            <Icon type='MaterialIcons' name='done' />                        
                        </Button>
                    </View>
                </Form>
            </View> 
        );
    }
}

const styles = StyleSheet.create({
    formContainer: {
        marginTop: 10,
        padding: 10,
    },
    editIcon:{
        color: '#28F1A6',
        fontSize: 26,
    },
    editBtn:{
        flex: 1,
        alignSelf: 'flex-end',
    }, 
    datePicker:{
        alignSelf: 'auto',
        paddingLeft: 10
    },
    footer:{
        position: 'relative',
        top: 350
    },
    saveBtn: {
        position:'relative',
        marginTop: 35,
    }
});

export default Reminder;

这是我的ReminderScreen.

import React, { Component } from 'react';
import { View, StatusBar } from 'react-native';
import PropTypes from 'prop-types';

import Reminder from '../components/Reminder';

const ReminderScreen = ({navigation}) => (
    <View >
        <Reminder navigation={navigation} >
            <StatusBar backgroundColor = "#28F1A6" />
         </Reminder >
    </View>
);

Reminder.propTypes = {
    navigation: PropTypes.object.isRequired
}

export default ReminderScreen;

标签: javascriptreactjsreact-nativeasyncstoragestoring-data

解决方案


函数中需要进行一些调整saveData并从 Asyncstorage 获取项目。

在 AsyncStorage 中存储数据时,只需将整个状态转换为字符串并保存即可。对于检索,只需将字符串转换为 JSON 对象并在setState函数中设置值。

请参阅下面的Remainder组件修改代码。

import React, { Component } from 'react';
import { View,StyleSheet, AsyncStorage, TextInput } from 'react-native';
import {
    Form,
    Button, Icon,
    DatePicker, Text
} from 'native-base';
import PropTypes from 'prop-types';
class Reminder extends Component {
    constructor(props) {
        super(props);
        this.state = {
            input: '',
            chosenDate: new Date(),
        };
        this.setDate = this.setDate.bind(this);
        this.handleChangeInput = this.handleChangeInput.bind(this);
        this.saveData = this.saveData.bind(this);
    }

    setDate(newDate) {
        this.setState({
            chosenDate: newDate
        });
    }

    handleChangeInput = (text) =>  {
        this.setState({input:text});
    }

    //On application loads, this will get the already saved data and set 
    //the state true when it's true.
    componentDidMount() {
        AsyncStorage.getItem("key").then((value) => {
            this.setState(JSON.parse(value));
        });
    }

    //save the input
    saveData() {
        AsyncStorage.setItem("key", JSON.stringify(this.state));
    }
    render() { 
      const {input} = this.state;
        return ( 
            <View>
                <Form style={styles.formContainer}>
                    <View style={styles.formView}>

                            < TextInput
                            placeholder = "Set your reminder"
                            onChangeText={this.handleChangeInput}
                            value={this.state.input}
                            />

                        <DatePicker
                            defaultDate={new Date()}
                            minimumDate={new Date(2018, 1, 1)}
                            maximumDate={new Date(2019, 12, 31)}
                            locale={"en"}
                            timeZoneOffsetInMinutes={undefined}
                            modalTransparent={false}
                            animationType={"fade"}
                            androidMode={"default"}
                            placeHolderText="Select date"
                            textStyle={{ color: "green" }}
                            placeHolderTextStyle={{ color: "#d3d3d3" }}
                            onDateChange={this.setDate}
                        />
                        <Text style={styles.datePicker}>
                            {this.state.chosenDate.toString().substr(4, 12)}
                        </Text>
                    </View>
                    <View style={styles.footer}>
                        <Button block success style={styles.saveBtn} 
                        onPress={ () => 
                            {this.saveData()
                            console.log('save data', value);}
                        } 
                           >
                            <Icon type='MaterialIcons' name='done' />                        
                        </Button>
                    </View>
                </Form>
            </View> 
        );
    }
}

const styles = StyleSheet.create({
    formContainer: {
        marginTop: 10,
        padding: 10,
    },
    editIcon:{
        color: '#28F1A6',
        fontSize: 26,
    },
    editBtn:{
        flex: 1,
        alignSelf: 'flex-end',
    }, 
    datePicker:{
        alignSelf: 'auto',
        paddingLeft: 10
    },
    footer:{
        position: 'relative',
        top: 350
    },
    saveBtn: {
        position:'relative',
        marginTop: 35,
    }
});

export default Reminder;

推荐阅读