首页 > 解决方案 > 在 AsyncStorage 中设置项目时,未定义不是对象

问题描述

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

在此处输入图像描述

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>
    );
  }
}

标签: react-nativeasyncstorage

解决方案


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

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

代替

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

为了获得最佳实践,请使用 try and catch

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

推荐阅读