问题描述
我在这里遗漏了什么? 在这一点上,我只想看到它写一个值并检索一个值。通过设置变量“ appType”,我可以查看它是否有效。这不是因为“ appType”的初始值没有改变。我可以通过加载哪个页面来知道这一点。我需要这些信息来确定首先要加载哪个页面。
import 'react-native-gesture-handler';
import React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import AsyncStorage from '@react-native-community/async-storage';
import SpMyPage from './screens/s_mypg';
import UsMyPage from './screens/u_mypg';
import UsRegPage from './screens/u_regs';
function checkAsyncStorage(){
var appType = '';
const storeData = async () => {
try {
await AsyncStorage.setItem('random_time','50000')
} catch (e) {
// saving error
}
}
const getData = async () => {
try {
const value = await AsyncStorage.getItem('random_time')
if(value !== null) {
// value prevIoUsly stored
appType = 'S';
}
else {
appType = 'U';
}
} catch(e) {
// error reading value
appType = 'U';
}
}
return appType;
}
function PreHomeScreen() {
var appType = checkAsyncStorage();
if (appType == 'S') {
return <SpMyPage />;
}
else {
if (appType == 'U') {
return <UsMyPage />;
}
else {
return <UsRegPage />;
}
}
}
/* ************************************************************************** */
const Stack = createStackNavigator();
function App() {
return (
<>
<NavigationContainer>
<Stack.Navigator
initialRouteName = "PreHomeScreen"
screenoptions={{
headerShown: false,}}>
<Stack.Screen name="PreHomeScreen" component={PreHomeScreen} />
<Stack.Screen name="SpMyPage" component={SpMyPage} />
<Stack.Screen name="UsMyPage" component={UsMyPage} />
<Stack.Screen name="UsRegPage" component={UsRegPage} />
</Stack.Navigator>
</NavigationContainer>
</>
);
};
export default App;
解决方法
我认为导入AsynStorage的正确方法是
import AsyncStorage from '@react-native-community/async-storage';
这是回购中的一个例子。 https://github.com/react-native-community/async-storage/blob/master/example/examples/GetSetClear.js
,我最初的目标是使用AsyncStorage。 我按照示例显示的方式进行了编码。
但是,我发现显然不需要在AsyncStorage方法周围包裹“异步函数”。因此,也不需要“等待”。不知道这是否会引起问题,但现在看来可以。
function checkAsyncStorage(){
var appType = '';
try {
AsyncStorage.setItem('random_time','50000')
} catch (e) {
// saving error
}
try {
const value = AsyncStorage.getItem('random_time')
if(value !== null) {
// value previously stored
appType = 'S';
}
else {
appType = '';
}
} catch(e) {
// error reading value
appType = 'U';
}
return appType;
}
,
// import语句应类似于:
import AsyncStorage from '@react-native-community/async-storage';
//用于检索以前存储的数据的函数(在此示例中为“ userId”)
retrieveData = async () => {
try {
const userId = await AsyncStorage.getItem('userId');
if (userId != null) {
console.log(userId);
}
} catch (e) {
console.log(e);
}
};
//用于存储数据的函数(在此示例中为“ userId”)
storeData = async () => {
try {
await AsyncStorage.setItem('userId',value);
} catch (e) {
console.log(e);
}
};