我在react native app中使用react-navigation v2创建了一些标签。我创建了componentDidMount函数,其中调用了willFocus。第一次运行app并且第一次选择了我想要的选项卡,willFocus没有执行。但当我转到不同的选项卡并返回到该选项卡时,现在将执行。是什么原因会导致第一次没有执行焦点并且第二次正常工作?
所需的选项卡componentDidMount函数
componentDidMount(){
const {navigation} = this.props;
navigation.addListener ('willFocus', async () =>{
console.log("willFocus runs"
});
}
选项卡导航器与其他导航器嵌套,但我只显示下面的选项卡导航器
TabNav: createBottomTabNavigator(
{
TAB1: Screen1,
TAB2: Screen2,
TAB3: Screen3,
TAB4: Screen4,
TAB5: Screen5,
// Map: MapScreen
},
{
initialRouteName: 'Bar',
transitionConfig: NavigationConfig,
navigationOptions: ({navigation})=>({
tabBarIcon: ({focused, tintColor})=>{
const { routeName } = navigation.state;
let iconName, iconSize;
switch(routeName) {
case "TAB1":
iconName = `icon1`;
break;
case "TAB2":
iconName = `icon2`;
break;
case "TAB3":
iconName = `icon3`;
break;
case "TAB4":
iconName = `icon4`;
break;
case "TAB5":
iconName = `icon5`;
break;
default:
break;
}
return <Icon name={iconName} color={tintColor} type="FontAwesome" />;
},
}),
tabBarOptions: {
activeTintColor: 'black',
inactiveTintColor: 'grey',
activeBackgroundColor: '#abaf9b',
labelStyle: {
fontSize: 12,
},
// style for tabbar
style: {
backgroundColor: '#ffffff',
height: 60,
justifyContent: 'space-around',
alignContent: 'center',
alignItems: 'center',
},
// style for tab
tabStyle: {
paddingTop: 7,
paddingBottom: 7
}
},
}
),
我也有这个问题,据报道它是一个反应导航的错误。查看this问题了解详情。
我有两个建议来解决这个问题。
PS:再次检查你的功能并确保两次调用该功能不会导致任何副作用
componentDidMount(){
console.log("willFocus runs") // calling it here to make sure it is logged at initial start
const {navigation} = this.props;
navigation.addListener ('willFocus', async () =>{
console.log("willFocus runs") // calling it here to make sure it is logged at every time screen is focused after initial start
});
}