首页 > 解决方案 > 无法从 react-native 中的 asyncStorage 获取价值

问题描述

我总是从反应原生应用程序中的 asyncStorage 获得“空”值。你能建议我适当的语法吗?

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

export const getStorageKey = async (key) => {
    const value = await AsyncStorage.getItem(key);
    return value; 
} 

export const setStorageKey = async (key, value) => {
    await AsyncStorage.setItem(key, value);
}

我尝试在 HTTP 拦截器中获取价值

 import { getStorageKey } from '../meta/storage';

 $http.interceptors.request.use((request) => {
    if(request.method === 'post') {
        request.data  = request.data ? request.data: {} 
        request['data']['user_id'] = getStorageKey('t_user_id');
        return request;
    }
 })

标签: react-native-androidasyncstorage

解决方案


Acc to link。您应该正确安装和链接库。如果链接没有正确执行,请按照说明手动链接react-native 链接 @react-native-community/async-storage。另外我正在分享一个示例代码t 使用这个库,但会解决异步存储使用的适当语法问题。希望能帮助到你。

import React, { Component } from 'react';

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

export default class App extends Component {
  constructor() {
    super();
    this.state = {
      textInputData: '',
      getValue: '',
    };
  }
  set = () => {
    if (this.state.textInputData) {
      AsyncStorage.setItem('any_key_here', this.state.textInputData);
      this.setState({ textInputData: '' });

      alert('Data successfully set');
    } else {
      alert('Please fill data');
    }
  };
  get = () => {
    AsyncStorage.getItem('any_key_here').then(value =>
      this.setState({ getValue: value })
    );
  };
  render() {
    return (
      <View style={styles.MainContainer}>
        <TextInput
          placeholder="Enter value to set"
          value={this.state.textInputData}
          onChangeText={data => this.setState({ textInputData: data })}
          underlineColorAndroid="transparent"
          style={styles.TextInputStyle}
        />
        <TouchableOpacity onPress={this.set} style={styles.button}>
          <Text style={styles.buttonText}> SET VALUE </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.get} style={styles.button}>
          <Text style={styles.buttonText}> GET VALUE </Text>
        </TouchableOpacity>
        <Text style={styles.text}> {this.state.getValue} </Text>
      </View>
    );
  }
}
const styles = StyleSheet.create({
  MainContainer: {
    alignItems: 'center',
    flex: 1,
    justifyContent: 'center',
    margin: 20,
  },
  TextInputStyle: {
    textAlign: 'center',
    height: 40,
    width: '100%',
    borderWidth: 1,
    borderColor: '#606070',
    borderRadius: 30,
  },
  button: {
    width: '100%',
    height: 40,
    padding: 10,
    backgroundColor: '#606070',
    marginTop: 10,
    borderRadius: 30,
  },
  buttonText: {
    color: '#fff',
    textAlign: 'center',
  },
  text: {
    fontSize: 20,
    textAlign: 'center',
  },
});

推荐阅读