代码之家  ›  专栏  ›  技术社区  ›  Nauman Tanwir

react native:如何使用异步存储存储完整状态及其所有道具

  •  0
  • Nauman Tanwir  · 技术社区  · 7 年前

    Reminder Component 以一个简单的形式包含一个 TextInput 从…起 react-native DatePicker native-base submit 要在单击时存储值,请单击。

    我正在努力实施 AyncStorage 本地存储这些值,然后在另一个屏幕上显示。但我不能这样做,因为我得到一个错误“值未定义”

    无论是什么博客帖子和啧啧称奇,此人只存储了一项财产。我想存储完整的状态,即输入字段和单击保存按钮的日期。

    这是我的 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;
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   kumar k    7 年前

    在这个过程中需要一些调整 saveData

    在异步存储中存储数据时,只需将整个状态转换为字符串并保存即可。对于检索,只需将字符串转换为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;
    
    推荐文章