0

我正在尝试从 AsyncStorage 中获取存储值。但它给出了 null is not an object 错误。这是我的代码。

import React, { Component } from 'react';
import { AsyncStorage, Image, View, StatusBar } from 'react-native';
import { connect } from 'react-redux';
import { Container, Button, H3, Text, Header, Title, Content, Icon, Footer, FooterTab, Left, Right, Body } from 'native-base';

import { openDrawer } from '../../actions/drawer';
import styles from './styles';
import Anatomy from '../anatomy/index.js';

const launchscreenBg = require('../../../img/abc.png');
const launchscreenLogo = require('../../../img/mob_app_bg.png');

var STORAGE_KEY_USER = '@ExpLocal:user';

class Home extends Component { // eslint-disable-line

  componentDidMount() {
    this._loadInitialState().done();
  }

  async _loadInitialState() {
    try {
      var user = await AsyncStorage.getItem(STORAGE_KEY_USER);
      if (user !== null){
        this.setState({selectedUser: user});
        this._appendMessage('Logged In User: ' + user);
      } else {
        this._appendMessage('Empty');
      }
    } catch (error) {
      this._appendMessage('AsyncStorage error: ' + error.message);
    }
  }

  getInitialState() {
    return {
      selectedUser: null,
      messages: [],
    };
  }

  static propTypes = {
    openDrawer: React.PropTypes.func,
  }

  render() {
    this._loadInitialState().done();
    // var loggedUser = this.state.selectedUser;
    if(this.state.selectedUser !== null){
      return (
        <Container style={styles.container}>
        <Header>
        <Left>
        <Button transparent onPress={this.props.openDrawer}>
        <Icon name="ios-menu" />
        </Button>
        </Left>
        <Body>
        <Title>Home</Title>
        </Body>
        <Right />
        </Header>
        </Container>
        );
    }else{
      return (
        <Anatomy />
        );
    }

  }
}

function bindActions(dispatch) {
  return {
    openDrawer: () => dispatch(openDrawer()),
  };
}

const mapStateToProps = state => ({
  navigation: state.cardNavigation,
  themeState: state.drawer.themeState,
  routes: state.drawer.routes,
});

export default connect(mapStateToProps, bindActions)(Home);

给出以下错误 null is not an object (evalating 'this.state.selectedUser') E:\REACT_NATIVE_PROJECTS\NativeBase-KitchenSink-master\js\components\home\index.js:49:18 我做错了什么?

4

2 回答 2

0

你可以这样使用:

AsyncStorage.getItem("STORAGE_KEY_USER").then((value) => {
   var user = value;
  //Your functionalities
}).catch((error) => {
  //Catch Block
});
于 2017-06-06T11:23:35.370 回答
0

您可以检查变量是否具有实际值。换句话说

if( value ) {}

如果有值,则为真,如果没有,则为

于 2017-06-06T11:24:38.680 回答