RN AsyncStorage的使用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_37695006/article/details/82664519

做web的时候保存数据常用的是cookie或者localstorage,那在移动端用什么呢?RN提供了AsyncStorage!

代码走起:

AsyncStorage在RN里自带的,不用npm install,直接引用即可~

import { View, Text, StyleSheet, AsyncStorage } from 'react-native';

操作就是增删改查,先是增(存)改同样的道理,同样的KEY,再存一次就是覆盖,自然就是改了。

    //保存数据
    asSave = () => {
        AsyncStorage.setItem(AS_KEY, this.state.valueCustom, (error) => {
            if (!error) {
                this.toast.show('保存数据成功', DURATION.LENGTH_SHORT);
            } else {
                this.toast.show('保存数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //查询保存的数据
    asQuery = () => {
        AsyncStorage.getItem(AS_KEY, (error, result) => {
            if (!error) {
                if (result !== '' && result !== null) {
                    // this.toast.show('查询到的内容是:' + result, DURATION.LENGTH_SHORT);
                    this.setState({
                        valueCustom: result,
                    });
                } else {
                    this.toast.show('未找到指定保存的内容!', DURATION.LENGTH_SHORT);
                }
            } else {
                this.toast.show('查询数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //删除已经保存的数据
    asDelete = () => {
        AsyncStorage.removeItem(AS_KEY, (error) => {
            if (!error) {
                this.toast.show('删除数据成功', DURATION.LENGTH_SHORT);
                this.setState({
                    valueCustom: "",
                });
            } else {
                this.toast.show('删除数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

完成的demo如下:
 

import React, { Component } from 'react';
import { View, Text, StyleSheet, AsyncStorage } from 'react-native';
import Toast, {DURATION} from 'react-native-easy-toast';
import {Container, Header, Title, Content, Button} from 'native-base';
import { Overlay, Label, Select, Button as TButton} from 'teaset';

//AsyncStorage是以键值对的形式保存数据 ,诸如安卓中SharedPreferences一样
const AS_KEY = "hm_deviceCode"

export default class SetDevice extends Component {
    constructor(props) {
        super(props);
        this.state = {
            valueCustom: "",  
        };
        this.customItems = [
            {
              text: 'test01',
              value: "1111",
            },
            {
              text: 'test02',
              value: "2222",
            }
        ];
    }

    componentDidMount() {
        this.asQuery();
    }

    //查询保存的数据
    asQuery = () => {
        AsyncStorage.getItem(AS_KEY, (error, result) => {
            if (!error) {
                if (result !== '' && result !== null) {
                    // this.toast.show('查询到的内容是:' + result, DURATION.LENGTH_SHORT);
                    this.setState({
                        valueCustom: result,
                    });
                } else {
                    this.toast.show('未找到指定保存的内容!', DURATION.LENGTH_SHORT);
                }
            } else {
                this.toast.show('查询数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //保存数据
    asSave = () => {
        AsyncStorage.setItem(AS_KEY, this.state.valueCustom, (error) => {
            if (!error) {
                this.toast.show('保存数据成功', DURATION.LENGTH_SHORT);
            } else {
                this.toast.show('保存数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    //删除已经保存的数据
    asDelete = () => {
        AsyncStorage.removeItem(AS_KEY, (error) => {
            if (!error) {
                this.toast.show('删除数据成功', DURATION.LENGTH_SHORT);
                this.setState({
                    valueCustom: "",
                });
            } else {
                this.toast.show('删除数据失败', DURATION.LENGTH_SHORT);
            }
        })
    }

    onSelected = (item, index) => {
        this.setState({
            valueCustom: item.value
        },()=>{
            this.asSave();
        });
    }

    render() {
        return (
            <Container>
                <Header>
                    <Title>
                        <Text style={{
                            lineHeight: 53,
                        }}>设备配置</Text>
                    </Title>
                </Header>

                <Content style={styles.content}>
                    <View style={{
                        display: 'flex',
                        flexDirection: 'row',
                        alignItems: "center",
                        justifyContent: "space-around"
                    }}>
                        <Label size='md' text='请选择当前设备:' />
                        <Select
                            style={{width: 200, backgroundColor: '#fcf8e3', borderColor: '#8a6d3b'}}
                            value={this.state.valueCustom}
                            valueStyle={{flex: 1, color: '#8a6d3b', textAlign: 'center'}}
                            items={this.customItems}
                            getItemValue={(item, index) => item.value}
                            getItemText={(item, index) => item.text}
                            iconTintColor='#8a6d3b'
                            placeholder='Select item'
                            pickerTitle='已有设备'
                            onSelected={(item, index) => this.onSelected(item, index)}
                        />
                        <TButton title='清除' onPress={() => this.asDelete()} />
                    </View>
                </Content>
                <Toast ref={v => this.toast = v}/>
            </Container>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#F5FCFF'
    },
    content: {
        margin: 5
    },
});

猜你喜欢

转载自blog.csdn.net/weixin_37695006/article/details/82664519
RN
今日推荐