如何在 alert onpress 中使用 react 导航?

问题描述 投票:0回答:1

我在使用 react 导航 v5。

我想在用户按 "OK "键时,从警报中导航到登录界面,但目前出现错误>&gt.找不到变量:导航。

找不到变量:导航

功能如下。

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') << 这部分不能导航。

谁能帮帮我?

谢谢

javascript react-native expo react-navigation react-navigation-v5
1个回答
2
投票

因为你没有把导航传递给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>
  );
}

0
投票

onPress应该是一个函数声明,当按下时将被触发

onPress: () => navigation.navigate('Login')
© www.soinside.com 2019 - 2024. All rights reserved.