这是一个常见问题,React Native尝试在从AsyncStorage获取值之前进行渲染.我已经在几个地方看到了解决方案,但由于某些原因它对我来说根本不起作用.也许是因为我使用的是React Native 25.1?它只会无限期地停留在"正在加载..."上.如果我在渲染上运行控制台登录以显示isLoading(没有if方法)它返回false,然后true理论上它应该工作.但是通过该if方法使其永久停留在"正在加载"并且日志仅返回false.
import React, { Component } from 'react';
import {
Text,
View,
AsyncStorage
} from 'react-native';
class MainPage extends Component {
constructor(props: Object): void {
super();
this.state = {
isLoading: false,
};
}
componentWillMount() {
AsyncStorage.getItem('accessToken').then((token) => {
this.setState({
isLoading: false
});
});
}
render() {
if (this.state.isLoading) {
return <View><Text>Loading...</Text></View>;
}
// this is the content you want to show after the promise has resolved
return <View/>;
} …Run Code Online (Sandbox Code Playgroud) 将"unique Id"保存为react native中的会话变量
我如何在Asyncstorge中设置多个值?因为我正在尝试设置token和user_id。这些是服务器响应值。这就是响应的样子
json
{ error: 0,
data: 'User registered Successfully',
userData:
{ pwd: 'lmlmlm',
phone_no: '9898989',
user_name: '',
status: 1,
date: 2018-10-24T07:12:20.656Z },
user_id: 60,
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.' }
Run Code Online (Sandbox Code Playgroud)
在响应本机之后,我在用户注册后就这样写了。
.then((response) => response.json())
.then((responseData) =>
{
console.log(responseData);
AsyncStorage.setItem('id_token', responseData.token),
AsyncStorage.setItem('user_id', responseData.user_id),
Actions.firstScreen();
});
Run Code Online (Sandbox Code Playgroud)
而在我的主页,我访问token和user_id内AsyncStorage作为
AsyncStorage.getItem('id_token').then((usertoken) =>{
this.setState({'id_token' : usertoken});
console.log(usertoken);
})
AsyncStorage.getItem('user_id').then((uid) => {
this.setState({'user_id': uid});
console.log(uid);
})
Run Code Online (Sandbox Code Playgroud)
但是我只得到token的uid控制台结果变为null。但是当我进行控制台操作时,其中包含responseData值。请帮助我
我试图在 AsyncStorage 中存储图片,但我不知道该怎么做,我应该存储 uri 还是路径?
\n\n我尝试过的有点废话,但我尝试过这个:
\n\nstate = {\n avatarSource: null,\n avatarSource2: null,\n}\n\nconstructor(props) {\n super(props);\n this.state = {\n modalVisible: false,\n images: [{\n url: \'\',\n }],\n }\n this.setModalVisible = this.setModalVisible.bind(this)\n}\n\nsaveData() {\n AsyncStorage.getItem("uri");\n}\nRun Code Online (Sandbox Code Playgroud)\n\n然后当我选择我的图像时使用这个:
\n\nselectImage = async () => {\n ImagePicker.showImagePicker({ nodata: true, mediaType: \'photo\' }, (response) => {\n console.log(\'Response = \', response);\n\n if (response.didCancel) {\n console.log(\'User cancelled image picker\');\n } else if (response.error) {\n console.log(\'ImagePicker Error: \', response.error);\n } else if (response.customButton) {\n console.log(\'User tapped custom button: …Run Code Online (Sandbox Code Playgroud) function CategoryCard (props) {
const [done, setDone] = React.useState(null);
let check;
React.useEffect(() => {
async function checkData() {
check = await getData(props.path);
// prints CORRECTLY
console.log(check);
}
checkData();
//prints INCORRECTLY
console.log(check);
setDone(true);
}, []);
return (
<View>
{done ? (
<Text>{check}</Text>
):(
<View style={[styles.container, styles.horizontal]}>
<ActivityIndicator size="large" color="#99ff99" />
</View>
)}
</View>
);
}
Run Code Online (Sandbox Code Playgroud)
如何从异步函数获取值到反应本机的常规函数中?在上面的代码中,第一个 console.log 打印预期值,但第二个 console.log 给出未定义的值,就好像异步函数从未对变量检查产生任何影响一样。我需要 check from 的值getData(props.path)才能将其显示在<Text>组件中。
有任何想法吗?
async function getTokenFromAsync() {
const userToken = await AsyncStorage.getItem('@User_Token');
return userToken;
}
export default {getTokenFromAsync};
Run Code Online (Sandbox Code Playgroud)
我试图从 asyncStorage 获取 userToken 但它返回给我这个 {"_U": 0, "_V": 0, "_W": null, "_X": null},我使用 React Native
当我的 AsyncStorage 项为空“可能未处理的承诺拒绝(id:0)”时,我收到以下警告消息所以我的问题是:如何处理承诺拒绝?
我的代码:
componentDidMount() {
try {
// This warning only appears when 'connections' item is empty
AsyncStorage.getItem('connections').then((token) => {
token = JSON.parse(token);
const getSectionData = (dataBlob, sectionId) => dataBlob[sectionId];
const getRowData = (dataBlob, sectionId, rowId) => dataBlob[`${rowId}`];
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2,
getSectionData,
getRowData,
});
const {dataBlob, sectionIds, rowIds} = this.formatData(token);
this.setState({
dataSource: ds.cloneWithRowsAndSections(dataBlob, sectionIds, rowIds),
});
});
}catch(error) {
console.log(error);
} …Run Code Online (Sandbox Code Playgroud) 在我的本机应用程序中,我在本地存储了一个对象并检索了它,工作正常,但现在我想将另一个对象附加到前一个对象,就像我有两个对象:
const obj1 = {key1: keyone, key2: keytwo}
const obj2 = {key4: keyfour, key6: keysix}
Run Code Online (Sandbox Code Playgroud)
我想要的只是一个对象
{ key1: keyone, key2: keytwo }, { key4: keyfour, key6: keysix }
Run Code Online (Sandbox Code Playgroud)
我试图这样做:
const newVal = `${obj1}, ${obj2}`
Run Code Online (Sandbox Code Playgroud)
返回“对象对象”
我经历了 Object.assign() 和 lodash 的 .merge() 功能,但似乎它们正在合并对象中的公共字段。
我如何实现这一目标?
我正在测试我的 React-Native 应用程序,并希望从 AsyncStorage 中删除所有项目,以便从头开始测试应用程序。我有点困惑。
我读的官方文档,发现multiRemove和clear功能,但我不明白如何清除我的应用程序的所有项目(clear据我了解清楚所有应用程序的整个存储,我不敢用它),multiRemove仅删除键是我给它参数,但我想清除所有键。
我想我可以通过getAllKeys键值来完成它并一一删除它,但也许有更清晰的方法来做到这一点?:)
谢谢
PS:我试着喜欢这个:
clearAllData() {
AsyncStorage.multiRemove([]).then(() => alert('success'));
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用......
我有以下 React Native 模块:
_localStorage.js
import AsyncStorage from '@react-native-community/async-storage';
const _storeData = async (key, value) => {
try {
await AsyncStorage.setItem(key, value);
} catch (error) {
console.log(error);
}
}
const _retrieveData = async (key) => {
try {
await AsyncStorage.getItem(key);
} catch (error) {
console.log(error);
}
}
export {_storeData, _retrieveData};
Run Code Online (Sandbox Code Playgroud)
应用头文件
import React from 'react';
import {Button} from 'react-native-paper';
import {_retrieveData, _storeData} from '../../utils/_localStorage'
const LoginButton = () => {
return (
<Button icon='login' color='yellow' onPress={() => navigation.navigate('Login')}>
Login
</Button> …Run Code Online (Sandbox Code Playgroud) asyncstorage ×10
react-native ×10
javascript ×5
reactjs ×2
android ×1
async-await ×1
asynchronous ×1
json ×1
promise ×1
session ×1