我想在“抽屉导航”的标题中显示登录的用户名。我将从异步存储或从API获得用户名。这是我的DrawerNavigator代码的样子。我正在AppNavigator中创建它。
const MyDrawerNavigator = createDrawerNavigator({
MainTab: {
screen: MainTabNavigator,
navigationOptions: {
title:'Home',
drawerIcon: ()=><SimpleLineIcons name={'home'} size={24} color={Colors.mediumGray}/>,
}},
Profile: {
screen: ProfileNavigator,
navigationOptions: {
title:'My Profile',
drawerIcon: ()=><SimpleLineIcons name={'user'} size={24} color={Colors.mediumGray}/>,
}
},
SignOut: {
screen: SignOut,
navigationOptions: {
title:'Sign Out',
drawerIcon: ()=><SimpleLineIcons name={'logout'} size={24} color={Colors.mediumGray}/>,
}},
},
{
// define customComponent here
contentComponent: props =>
<ScrollView>
<SafeAreaView style={{flex:1}} forceInset={{ top: 'always', horizontal: 'never' }}>
<View style={{width:'100%', backgroundColor: Colors.primary, height:40}}>
<DrawerHeader />
<Text>Your Own Header Area </Text>
</View>
<DrawerItems {...props} />
<Text>Your Own Footer Area After</Text>
</SafeAreaView>
</ScrollView>,
contentOptions: {
headerStyle: {
backgroundColor: 'white',
},
itemsContainerStyle: {
marginVertical: 140,
},
iconContainerStyle: {
opacity: 1
},
itemStyle: {
fontFamily: Typography.fontFamilyRegular,
fontWeight: 'normal'
},
labelStyle: {
fontFamily: Typography.fontFamilyRegular,
fontWeight: 'normal'
}
},
}
);
DrawerHeader是一个单独的类,我尝试在其中获取用户名。这是此类的样子
import React, {Component} from 'react';
import { Platform, TouchableOpacity, Image, View, Text } from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
export default class DrawerHeader extends React.Component {
constructor(props) {
super(props);
this.state = {
userId: null,
errorText: '',
activityData: '',
activityDataLoaded: false,
};
this._loadDataFromAsyncStorage();
}
_loadDataFromAsyncStorage = async () => {
const userToken = await AsyncStorage.getItem('@user_id');
alert('_bootstrapAsync in drawerheader'+userToken);
this.setState({
userId : userToken,
})
};
render() {
{!this.state.userId && this._loadDataFromAsyncStorage()}
if (this.state.userId){
return (
<View style={{ flexDirection: 'row' }}>
<Text>{this.state.userId}</Text>
<Text>Vikalp Jain</Text>
</View>
);
} else {
return (
<View style={{ flexDirection: 'row' }}>
<Text>No User Id</Text>
</View>
)
}
}
}
但这只是在标题中显示“无用户ID”。我已经确认user_id存在于异步存储中。这种方法有什么问题?
答案 0 :(得分:0)
问题是,我尚未导入AsyncStorage库。由于某些原因,它没有因此引发任何错误。