navigation.goBack 和 navigation.dispatch(e.data.action) 在 react native android 中有什么区别

What is the difference between navigation.goBack and navigation.dispatch(e.data.action) in react native android

我是 React Native 的新手,我有 android 的 React Native 应用程序,我正在使用 Navigation 5 导航到下一页。应用程序工作流是 loginScreen -> HomeScreen -> ExistingStockScreen -> ScanSkidBarcodeScreen -> ScanItemsScreen。 我在 ScanItemScreen 上使用此代码处理后退按钮按下。

 navigation.addListener('beforeRemove', (e) => {
 // Prevent default behavior of leaving the screen
            e.preventDefault();
            if (this.state.items[0].barCode !== "" && this.state.items[5].barCode !== "") {
             
                Alert.alert(
                    'Error!',
                    'You can only scan six items at a time.',
                    [
                    { text: "OK", style: 'cancel', onPress: () => { } },
                    ]
                );
            }
            else if (this.state.items[0].barCode !== "") {
              
                Alert.alert(
                    'Attention!',
                    'You have unsaved items. Please click on UPDATE STATUS first and go back.',

                    [{ text: "OK", style: 'cancel', onPress: () => { } },
                    {
                       text: 'Go Back',
                        style: 'destructive',
                        // If the user confirmed, then we dispatch the action we blocked earlier
                        // This will continue the action that had triggered the removal of the screen
                        onPress: () => navigation.dispatch(e.data.action),
                    },]

                );
            } else {
                navigation.dispatch(e.data.action)
            }
        })
    }

但是 navigation.dispatch(e.data.action) 代码将返回屏幕,但由于某种原因它会注销用户。 所以我想改用 navigation.goBack() 。 navigation.goBack() 和 navigation.dispatch(e.data.action) 有什么区别?

beforeRemove 事件在屏幕被移除时触发,这可能由于各种原因(例如 reset 或其他操作)而发生。虽然返回是触发它的方法之一,但它不是唯一的方法。

来自docs

  • 用户在堆栈中的屏幕上按下了后退按钮
  • 用户执行了向后滑动的手势
  • 调度了一些操作,例如 popreset,从状态中删除了屏幕

e.data.action 中的对象是指触发该事件的操作。通过使用 navigation.dispatch(e.data.action) 再次调度该操作,您可以在执行所需的任何检查后继续该操作,例如提示用户。

如果您不再发送事件而是尝试 goBack():

  • 这是不正确的行为 - 如果重置触发了事件,您应该继续重置(或触发事件的任何原因),而不是完全执行不同的操作
  • 无论如何都行不通,因为goBack只会触发事件,所以你会陷入提示循环

However navigation.dispatch(e.data.action) code is going to back screen but it logs out the user for some reason

React Navigation 不会与您的应用状态交互。如果您的用户在导航时被注销,那是您的代码中的错误,您需要调试和修复。