2017-11-25 129 views
4

我无法使用AsyncStorage setItem。以下是我的代码。所以我从TextInput那里得到这个名字,然后想把它存储在TouchableOpacityAsyncStorageonPress。我收到提示:无法在AsyncStorage中设置项目

enter image description here

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

我在做什么错?请帮忙。

回答

4

你需要从react-native

import { View, Text, StyleSheet, TextInput, TouchableOpacity , AsyncStorage} from 'react-native'; 

导入AsyncStorage您还需要保持asyncSetName功能

取消注释此行

this.asyncSetName = this.asyncSetName.bind(this) 

同样的结合通过@克里斯你的发现需要更改您的班级名称以便与AsyncStorage

012不同
+0

谢谢。我是否必须在构造函数(props)中绑定这个'this.asyncSetName = this.asyncSetName.bind(this)',并且像这样调用它:'onPress = {this.asyncSetName.bind(this)}'。 为什么我需要将它绑定两次? – Somename

+1

欢迎您......关于绑定,您需要绑定一次,我更喜欢使用构造函数中的一个 –

3
  1. 正如@Amir所说,您需要从react-native导入AsyncStorage以及保留绑定,因为他建议。
  2. 您可能想要将您的班级重命名为AsyncStorage以外的其他人
  3. 或者,您可能想要命名空间您的AsyncStorage密钥。通常在密钥的前面放置一个@AppName,所以最终的密钥最终将会是@AppName${this.state.name}。但是,再次,这是可选的,只是惯例。
相关问题