在AsyncStorage中设置项目时,Undefined不是对象

时间:2019-07-07 09:38:37

标签: react-native asyncstorage

在我的React Native应用程序中,我想将令牌存储到AsyncStorage中,但是尝试这样做时,它会发出以下警告。关于此类问题,我经历了很多SO解答,但无法解决提出解决方案。

enter image description here

SignupScreen.js

import React from "react";
import { View } from "react-native";
import { AsyncStorage } from '@react-native-community/async-storage'
import PhoneInput from "react-native-phone-input";
import {
  Button,
  Text,
  Form,
  Item as FormItem,
  Input,
  Label,
} from 'native-base';

export default class Signup extends React.Component {
  static navigationOptions = {
    drawerLabel: "Signup",
  };

  constructor(props) {
    super(props);
    this.state = {
      fname: "",
      mobile: "",
    };

  }

  setToken = async () => {
    //This is where the warning is throws
    await AsyncStorage.setItem('token', 'tokka').then(
      val => {
        if(val) this.props.navigation.navigate('Dashboard')
      }
    )
  }

  render() {
    return (
      <View style={{paddingTop: "40%"}}>
        <Text style={{textAlign: "center",fontSize: 40}}>OnTask</Text>
        <Text style={{fontSize: 20,textAlign: "center"}}>Signup</Text>
        <Form>
        <FormItem>
          <Label>First Name</Label>
          <Input />
        </FormItem>

        <Label style={{marginTop: "3%",marginLeft: "4%"}}>Mobile Number</Label>
          <PhoneInput
          ref="phone"
          style={{
            height: 50,
            padding: 10,            
            width: 300,
            marginLeft: "2%",
            marginBottom: "5%",
            borderRadius: 10
          }}
          onChangePhoneNumber={ number => this.setState({mobile: number})}
/>

        <Button full primary onPress={() => this.setToken()}>
          <Text> Sign Up </Text>
        </Button>

      </Form>
      </View>
    );
  }
}

1 个答案:

答案 0 :(得分:2)

问题是您导入AsyncStorage错误。请导入不带花括号的AsyncStorage。

import AsyncStorage from '@react-native-community/async-storage';

代替

import { AsyncStorage } from '@react-native-community/async-storage';

为获得最佳实践,请尝试并抓住

setToken = async () => {
  try {
    const val = await AsyncStorage.setItem('token', 'tokka');
    if(val) this.props.navigation.navigate('Dashboard')
  } catch (e) {
    console.log('error', e.message);
  }
}