【问题标题】:react native: how to store complete state and all it's props using AsyncStoragereact native:如何使用 AsyncStorage 存储完整状态及其所有道具
【发布时间】:2018-12-08 06:13:35
【问题描述】:

我有一个Reminder Component,其简单形式包括一个来自react-nativeTextInput 和一个来自native-baseDatePicker 和一个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;

【问题讨论】:

    标签: javascript reactjs react-native asyncstorage storing-data


    【解决方案1】:

    需要对 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;
    

    【讨论】:

    • 它工作得很好,但是当我重新加载页面时,它以某种奇怪的方式显示日期 imgur.com/a/y8T7DTS 。我已经分享了截图。请检查链接。
    • 取自chosenDate变量{this.state.chosenDate.toString().substr(4, 12)}的子字符串的问题。存储在存储中的日期格式,如2018-12-07T18:30。因此更改日期格式或相应更改代码。如果它解决了您的问题,请将其标记为答案。
    猜你喜欢
    • 1970-01-01
    • 2017-08-17
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    相关资源
    最近更新 更多