如何在 alert onpress 中使用反应导航?

how to use react navigation inside alert onpress?

我正在使用反应导航 v5,

我正在尝试在用户按“确定”时从警报导航到登录屏幕, 但目前无法使用错误 >>

can't find variable: navigation

函数如下:

async function handleSubmit(navigation) {
  try {
    const value = await AsyncStorage.getItem('storage_useremail');
    if (value !== null) {
      fetch('https://xxxxxx/logout', {
        method: 'POST',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email: value,
        }),
      }).then(res => res.json())
        .then(res => {
          // console.log(res.err_code)
          if (res.err_code == '0000') {
      Alert.alert('Notice',res.message + " (" + res.err_code + ")",[{ text: 'Yes', onPress: () => navigation.navigate('Login')} ]);
          } else {
            Alert.alert("Response:  " + res.err_code + " - " + res.message);
          }
        })
    }
  } catch (error) {
    // Error retrieving data
  }
}



function HomeNavigator() {
  return (
<AppStack.Navigator mode="modal" initialRouteName="Login" screenOptions={({ route, navigation }) => ({
  headerStyle: {
    backgroundColor: '#fb5b5a',
    borderBottomWidth: 0,
  },
  headerRight: () => (
    <Button
      onPress={() => handleSubmit()}
      // onPress={() => navigation.navigate('Login')}
      title="Logout"
      color="#fff"
    />
  ),
})}>
  <AppStack.Screen
    name="Home"
    component={HomeScreen}
    options={{
      title: 'Home',
    }}
  />
  <AppStack.Screen
    name="Memory"
    component={MemoryScreen}
    options={{
      title: 'Memory',
    }} />
</AppStack.Navigator>
  );
}

navigation.navigate('Login') << 这是无法导航的部分。

有人可以帮忙吗?

先致谢

onPress 应该是按下时触发的函数声明

onPress: () => navigation.navigate('Login')

因为你没有将导航传递给 handleSubmit

function HomeNavigator() {
  return (
<AppStack.Navigator mode="modal" initialRouteName="Login" screenOptions={({ route, navigation }) => ({
  headerStyle: {
    backgroundColor: '#fb5b5a',
    borderBottomWidth: 0,
  },
  headerRight: () => (
    <Button
      onPress={() => handleSubmit(navigation)} // <<<<<<<<<<<< Here
      // onPress={() => navigation.navigate('Login')}
      title="Logout"
      color="#fff"
    />
  ),
})}>
  <AppStack.Screen
    name="Home"
    component={HomeScreen}
    options={{
      title: 'Home',
    }}
  />
  <AppStack.Screen
    name="Memory"
    component={MemoryScreen}
    options={{
      title: 'Memory',
    }} />
</AppStack.Navigator>
  );
}