我有这个菜单,当用户登录时,我会在其中过滤按钮;我正在从单独的文件访问功能,以查看是否登录了用户。
从菜单
import { IsLogged } from '../GlobalFunctions';
const SubDrawer1 = ({ data, onChange }) => (
<View>
{
IsLogged() ? (
<View>
<TouchableOpacity onPress={()=>{onChange('LogoutScreen')}}>
<Text>Logout</Text>
</TouchableOpacity>
</View>
) : (<View />)
}
</View>
);
export default SubDrawer1;
从GlobalFunctions
export function IsLogged(){
AsyncStorage.getItem('userId').then((userId) => {
return userId ? true : false
})
}
在菜单中,我调出IsLogged()
函数,但在我进行console.log记录时,其值为undefined
。它应该返回true
或false
。
答案 0 :(得分:0)
因为AsyncStorage将花费一些时间,并且在该函数完成执行之前。 (因为JS中的所有内容都是异步的)
所以只需等待它完成物品的获取,
export function async IsLogged(){
let userId = await AsyncStorage.getItem('userId');
return userId ? true : false
}
答案 1 :(得分:0)
您正在尝试调用异步函数,因此您需要添加一些额外的代码。请尝试以下操作。
SubDrawer1
import { Text, View, TouchableOpacity } from "react-native";
import React, { Component } from "react";
import { IsLogged } from "../GlobalFunctions";
const SubDrawer1 = async ({ data, onChange }) => {
const status = await IsLogged();
if (status === true) {
return (
<View>
<View>
<TouchableOpacity
onPress={() => {
onChange("LogoutScreen");
}}
>
<Text>Logout</Text>
</TouchableOpacity>
</View>
</View>
);
} else {
return (
<View>
<View />
</View>
);
}
};
export default SubDrawer1;
'IsLogged()'全局函数
export function async IsLogged(){
let userId = await AsyncStorage.getItem('userId');
return userId ? true : false
}
“ SubDrawer1”使用类
...
import SubDrawer1 from "./SubDrawer1"; // import your 'SubDrawer1' component
var subDrawer1Component; // declare a variable for your rendering component
//Your main class
export default class ClassName extends Component<Props> {
componentDidMount() {
this.getComponentInfo(); //Call this method to get function
}
getComponentInfo = async () => {
subDrawer1Component = await SubDrawer1();// Will take the component
this.setState({ isDataGet: true });
};
render() {
return (
...
{subDrawer1Component}
...
);
}
}
...