react-native - 在 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>
);
}
}
解决方案
问题是您错误地导入了 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);
}
}
推荐阅读
- javascript - 猫鼬中的组成唯一ID
- angular - Ionic imagepicker 插件未安装错误
- angular - Angular 单元测试:服务函数返回的值
- google-cloud-pubsub - pubsub.projects.subscriptions.pull 失败并出现 INVALID_ARGUMENT
- sql - 用一个查询从不同的表中计数
- c++ - CERN ROOT:为命名空间中的外部“C”结构生成流光
- javascript - 操作列按钮在过滤 vuetable 时不会改变
- c - 奇怪的 fork() 行为(之前的 printf 被召回)
- windows - Powershell:通过 powershell 更新快捷方式的热键不起作用
- excel - 使用 VBA 检查用户名是否存在于范围内