无法在 AsyncStorage 中设置项目

Unable to setItem in AsyncStorage

我无法 setItem 使用 AsyncStorage。以下是我的代码。所以我从 TextInput 获取状态中的名称,然后想将其存储在 TouchableOpacityAsyncStorage onPress 中。我收到错误:

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

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

您还需要保留 asyncSetName 函数的绑定

取消注释这一行

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

另外正如@Chris 所发现的那样,您需要将您的 class 名称更改为不同于 AsyncStorage

  1. 正如@Amir 所说,您需要从 react-native 导入 AsyncStorage 并按照他的建议保持绑定。
  2. 此时您可能还想将 class 重命名为 AsyncStorage 以外的名称
  3. 您可能希望为您的 AsyncStorage 密钥命名空间。在密钥前面放置一个 @AppName 是很常见的,所以你的最终密钥最终会是 @AppName${this.state.name}。但同样,这是可选的,只是约定俗成的。