How to reset a specific stack navigator from outside of it?

时光怂恿深爱的人放手 提交于 2019-12-02 16:19:39

问题


I'm making an app using react-navigation with react-native.

The structure of my app is,

Main Tab
  - Tab 1 (Stack)
    - screen A
    - screen B
    - screen C
  - Tab 2 (Stack)
    - screen D
    - screen E
    - screen F

What I want to do is reset Tab 1 (Stack Navigator) at the specific time and do not navigate to Tab 1.

if a user is located in screen F, I just want to reset Tab 1 (Stack) without letting the user move to Tab 1.

So I think dispatching navigation actions should be triggered outside of these react components, somewhere like resetHelper.js

But I can't figure out how to reset a specific stack without navigating that stack.

Any help would be appreciated. Thanks in advance!


回答1:


Normally, if you were in a specific stack, you would reset via this.props.navigation.reset() but since you want to reset one stack from another stack you will need to use a NavigationService for the StackNavigator that needs to be reset.

Read this help guide to see how you can create a NavigationService.

Once you have a NavigationService setup, edit the NavigationService.js to this:

import { StackActions, NavigationActions } from 'react-navigation';

let _navigator;

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function reset(index = 0, actions) {
  _navigator.dispatch(
    StackActions.reset({
      index,
      actions
    })
  );
}

// add other navigation functions that you need and export them

export default {
  reset,
  setTopLevelNavigator,
};

Then from any function in any file, do this:

import {reset} from NavigationService.js
//your other code and functions here.
reset(0, actions)

Read more about it here.



来源:https://stackoverflow.com/questions/57705673/how-to-reset-a-specific-stack-navigator-from-outside-of-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!