无法在AsyncStorage中设置项目
问题描述:
我无法使用AsyncStorage setItem
。以下是我的代码。所以我从TextInput
那里得到这个名字,然后想把它存储在TouchableOpacity
的AsyncStorage
onPress
。我收到提示:无法在AsyncStorage中设置项目
import React, { Component } from 'react';
import { View, Text, StyleSheet, TextInput, TouchableOpacity} from 'react-native';
class AsyncStorage extends Component {
constructor(props) {
super(props);
this.state = {
name:''
}
//this.asyncSetName = this.asyncSetName.bind(this) //tried this too.
};
asyncSetName(){
let name = this.state.name
AsyncStorage.setItem('name', name);
}
render(){
<View>
<TextInput
placeholder='Set Name here'
onChangeText={(name) => this.setState({name})}
value={this.state.name}
autoCorrect={false}
></TextInput>
<TouchableOpacity
onPress={this.asyncSetName.bind(this)}
>
<Text>SetName</Text>
</TouchableOpacity>
</View>
}
}
我在做什么错?请帮忙。
答
你需要从react-native
import { View, Text, StyleSheet, TextInput, TouchableOpacity , AsyncStorage} from 'react-native';
导入AsyncStorage
您还需要保持asyncSetName
功能
取消注释此行
this.asyncSetName = this.asyncSetName.bind(this)
同样的结合通过@克里斯你的发现需要更改您的班级名称以便与AsyncStorage
答
- 正如@Amir所说,您需要从
react-native
导入AsyncStorage
以及保留绑定,因为他建议。 - 您可能想要将您的班级重命名为
AsyncStorage
以外的其他人 - 或者,您可能想要命名空间您的AsyncStorage密钥。通常在密钥的前面放置一个
@AppName
,所以最终的密钥最终将会是@AppName${this.state.name}
。但是,再次,这是可选的,只是惯例。
谢谢。我是否必须在构造函数(props)中绑定这个'this.asyncSetName = this.asyncSetName.bind(this)',并且像这样调用它:'onPress = {this.asyncSetName.bind(this)}'。 为什么我需要将它绑定两次? – Somename
欢迎您......关于绑定,您需要绑定一次,我更喜欢使用构造函数中的一个 –