Как сбросить экран до root при использовании StackNavigator и BottomTabNavigator в ReactNavigation - PullRequest
0 голосов
/ 30 марта 2020

Я видел много сообщений на эту тему, но ни одна не решает мою проблему.

У меня есть класс навигации, который позволяет мне создавать разные stackNavigator (с тем, что я могу назвать стартовым экраном, или initialRoute, если я правильно понятная документация по ReactNavigation).

Я также создал BottomTabNavigator, и каждая вкладка отправляет пользователю определенное значение c StackNavigator.

Моя проблема: - Я запускаю на главном экране и go на Screen2 (Домой -> Screen1 -> Screen2) (вниз в моем StackNavigator). - Я go на другой StackNavigator, используя мой BottomTabNavigator. - Я go вернулся на вкладку "Главная" в BottomTabNavigator и там непосредственно отображается экран 2.

Что я хочу: определить начальный экран для каждого из моих StackNavigator, а когда я go - один из затем, используя BottomTabNavigator, отображается этот стартовый экран, а не последний, отображаемый перед выходом.

Вот мой файл навигации:

const Tab = createBottomTabNavigator()

const HomeStack = createStackNavigator()
const MoneyStack = createStackNavigator()
const StuffStack = createStackNavigator()
const TestStack = createStackNavigator()

function HomeStackScreen() {
    return (
        <HomeStack.Navigator
            initialRouteName='Home'
            screenOptions={{
            headerStyle: {
                backgroundColor: '#003F5C',
            },
            headerTintColor: '#FB5B5A',
            }}>
            <HomeStack.Screen name="Home"
            component={Home} 
            options={({route, navigation}) => (
                {headerTitle: 'Home Page',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <HomeStack.Screen name="AddMoney"
            component={AddMoney} 
            options={({route, navigation}) => (
                {headerTitle: 'Prêt d\'argent',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <HomeStack.Screen name="AddStuff"
            component={AddStuff} 
            options={({route, navigation}) => (
                {headerTitle: 'Prêt d\'objet',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <HomeStack.Screen name="Settings"
            component={Settings} 
            options={({route, navigation}) => (
                {headerTitle: 'Settings',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <HomeStack.Screen name="TypesList"
            component={TypesList} 
            options={({route, navigation}) => (
                {headerTitle: 'Les types',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
        </HomeStack.Navigator>
    )
}

function MoneyStackScreen() {
    return(
        <MoneyStack.Navigator
        screenOptions={{
            headerStyle: {
                backgroundColor: '#003F5C',
            },
            headerTintColor: '#FB5B5A',
            }}>
            <MoneyStack.Screen name="LendList" 
            component={LendList}
            initialParams={{ type: 'Money' }}
            options={({route, navigation}) => (
                {headerTitle: 'Mes prêts',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <MoneyStack.Screen name="AddMoney"
            component={AddMoney} 
            options={({route, navigation}) => (
                {headerTitle: 'Prêt d\'argent',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <MoneyStack.Screen name="ItemDetails"
            component={ItemDetails} 
            options={({route, navigation}) => (
                {headerTitle: 'Détails',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
        </MoneyStack.Navigator>
    )
}

function StuffStackScreen() {
    return(
        <StuffStack.Navigator
        screenOptions={{
            headerStyle: {
                backgroundColor: '#003F5C',
            },
            headerTintColor: '#FB5B5A',
            }}>
            <StuffStack.Screen name="LendList" 
            component={LendList}
            initialParams={{ type: 'Stuff' }}
            options={({route, navigation}) => (
                {headerTitle: 'Mes prêts',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <StuffStack.Screen name="AddStuff"
            component={AddStuff} 
            options={({route, navigation}) => (
                {headerTitle: 'Prêt d\'objet',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <StuffStack.Screen name="ItemDetails"
            component={ItemDetails} 
            options={({route, navigation}) => (
                {headerTitle: 'Détails',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
        </StuffStack.Navigator>
    )
}

function TestStackScreen() {
    return(
        <TestStack.Navigator
        screenOptions={{
            headerStyle: {
                backgroundColor: '#003F5C',
            },
            headerTintColor: '#FB5B5A',
            }}>
            <TestStack.Screen name="Test"
            component={Test} 
            options={({route, navigation}) => (
                {headerTitle: 'Test',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
            <TestStack.Screen name="ItemDetails"
            component={ItemDetails} 
            options={({route, navigation}) => (
                {headerTitle: 'Détails',
                route: {route}, 
                navigation: {navigation}}
            )}
            />
        </TestStack.Navigator>
    )
}

function App() {
    return(
        <NavigationContainer>
            <Tab.Navigator
                screenOptions={({ route }) => ({
                    tabBarIcon: ({ focused, color, size }) => {
                        let iconName;
                        let prefix;

                        (Platform.OS === 'android')? prefix = 'md-' : prefix = 'ios-'

                        if (route.name === 'Home') {
                            iconName = 'home'
                        } else if (route.name === 'Money') {
                            iconName = 'cash'
                        } else if (route.name === 'Stuff') {
                            iconName = 'cube'
                        } else if (route.name === 'Test') {
                            iconName = 'beaker'
                        }

                        iconName = prefix + iconName

                        // You can return any component that you like here!
                        return <Ionicons name={iconName} size={size} color={color} />;
                    },
                })}
                tabBarOptions={{
                    activeTintColor: '#FB5B5A',
                    activeBackgroundColor: 'white',
                    inactiveTintColor: '#FB5B5A',
                    inactiveBackgroundColor: '#003F5C'
                }}
            >
                <Tab.Screen name='Home' component={HomeStackScreen} initialRouteName='Home' />
                <Tab.Screen name='Money' component={MoneyStackScreen} />
                <Tab.Screen name='Stuff' component={StuffStackScreen} />
                <Tab.Screen name='Test' component={TestStackScreen} />
            </Tab.Navigator>
        </NavigationContainer>
    )
}

export default App

Здесь часть «Домашний файл», где я пытался использовать « Функция «Сброс» из ReactNavigation

const resetAction = CommonActions.reset ({индекс: 0, маршруты: [{name: 'Home'},],})

экспорт класса по умолчанию Home расширяет React .Компонент {

constructor(props) {
    super(props)
    this._goToSettings = this._goToSettings.bind(this)

    this.state = { 
        totalMoney: 0,
        totalQuantity: 0,
        isLoading: true
    }
}

componentDidMount(){
    const { navigation } = this.props

    this.focusListener = navigation.addListener('focus', () => {
        this._getData()
        console.log('coucou')
        navigation.dispatch(resetAction)
    });
    this._updateNavigationParams()
}

componentWillUnmount() {
    // Remove the event listener before removing the screen from the stack
    this.focusListener();
}

}

Не стесняйтесь спрашивать, если вам нужна дополнительная информация.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...