无法从react-native的asyncStorage获取价值

时间:2019-05-17 16:46:16

标签: react-native-android asyncstorage

我总是在React Native App中从asyncStorage获取一个'null'值。您能给我建议合适的语法吗?

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

1 个答案:

答案 0 :(得分:0)

访问link。请正确安装并链接库。如果未正确使用 react-native链接@ react-native-community / async-storage < / strong>。我还将分享一个示例代码,该代码不使用该库,但可以解决您的异步存储使用的适当语法问题。希望对您有所帮助。

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',
  },
});