null不是对象

时间:2017-06-06 11:18:01

标签: android react-native asyncstorage

我正在尝试从AsyncStorage获取存储值。但它给出null不是对象错误。 这是我的代码。

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不是对象(评估'this.state.selectedUser')  E:\ REACT_NATIVE_PROJECTS \ NativeBase-的KitchenSink主\ JS \分量\家\ index.js:49:18 我做错了什么?

2 个答案:

答案 0 :(得分:0)

您可以这样使用:

AsyncStorage.getItem("STORAGE_KEY_USER").then((value) => {
   var user = value;
  //Your functionalities
}).catch((error) => {
  //Catch Block
});

答案 1 :(得分:0)

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

if( value ) {}

如果有值,则 true ;如果没有,则 false