我正在用本机构建一个应用程序。我正在尝试使用switchNavigator在导航中动态设置初始路线名称。这是我的代码:
Navigation.js
import { createStackNavigator, createAppContainer, createSwitchNavigator } from 'react-navigation'
import homeDisconnect from '../screens/homeDisconnect.js'
import Login from '../screens/Login'
import Register from '../screens/Register'
import Home from '../screens/Home'
import AuthLoading from '../screens/AuthLoading'
const AppStack = createStackNavigator(
{
Home: {
screen: Home,
navigationOptions: {
headerTitle: 'Accueil',
headerLeft: null,
gesturesEnabled: false
}
}
}
)
const AuthStack = createStackNavigator(
{
homeDisconnect: {
screen: homeDisconnect,
navigationOptions: {
headerTitle: null,
headerLeft: null,
header: null
}
},
Login: {
screen: Login,
navigationOptions: {
headerTitle: 'S\'identifier',
headerLeft: null
}
},
Register: {
screen: Register,
navigationOptions: {
headerTitle: 'S\'inscrire'
}
}
},
{
headerLayoutPreset: 'center',
initialRouteName: 'homeDisconnect'
}
)
export default createAppContainer(createSwitchNavigator(
{
AuthLoading: AuthLoading,
AppStack: AppStack,
AuthStack: AuthStack,
}
));
AuthLoading.js
import React, { Component } from 'react'
import {ActivityIndicator, StatusBar, StyleSheet, View} from 'react-native'
import {AppStack, AuthStack} from '../navigation/StackNavigation'
import { connect } from 'react-redux'
class AuthLoading extends Component {
constructor() {
super();
}
componentDidMount(){
this._bootstrapAsync()
}
_bootstrapAsync = async () => {
console.log(this.props)
const userToken = this.props.token
this.props.navigation.navigate(userToken ? 'App' : 'Auth');
};
render() {
return (
<View style={styles.container}>
<ActivityIndicator />
<StatusBar barStyle="default" />
</View>
);
}
}
const mapStateToProps = (state) => {
return state
}
export default connect(mapStateToProps)(AuthLoading);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
App.js
import {AuthLoading} from './src/screens/AuthLoading'
export default class App extends Component {
render() {
return (
<View>
<AuthLoading></AuthLoading>
</View>
)
}
}
->从'../navigation/StackNavigation'导入{AppStack,AuthStack},那样做是不可能的吗?我遇到了这个错误:
路由“ AuthLoading”的组件必须是React组件。
我在做什么错了?
答案 0 :(得分:0)
SwitchNavigator知道可以在同一SwitchNavigator中在屏幕/堆栈之间进行导航,因此我建议以这种方式进行导航:
userToken ?
this.props.navigation.navigate('AppStack') : this.props.navigation.navigate('AuthLoading')
并且您不需要此导入,因此将其删除:
import {AppStack, AuthStack} from '../navigation/StackNavigation'
Navigation.js:
export default MainNavigator = createSwitchNavigator(
{
AuthLoading: AuthLoading,
AppStack: AppStack,
AuthStack: AuthStack,
}
});
现在在App.js
中更改代码:
import MainNavigator from './src/screens/AuthLoading'
export default class App extends Component {
render() {
return (
<View>
<MainNavigator />
</View>
)
}
}