react-native-android - 无法从 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;
}
})
解决方案
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',
},
});
推荐阅读
- javascript - 在 JavaScript 中访问 Map 对象内的对象和数组
- c# - VS 在使用通用 Blazor 视图的错误列表中显示错误的问题
- spring - 我们可以对 Pig UDF 进行 bean 注入吗
- javascript - 如何在 Javascript/HTML 中存储输入值
- git - 如果我在没有设置用户名和电子邮件地址的情况下进行第一次推送会发生什么?
- java - Bson过滤器MongoDB
- c++ - 如何正确升级您的 OpenMP 版本?
- c - Creating Bidirectional Pipe in C For Both Reading and Writing Using One Pipe (Linux)
- node.js - Mongoose 聚合并获得点赞数
- c# - 使用 Access 数据库的实体框架查询 DaysOfWeek