如何修复有效载荷的动作“NAVIGATE”?

How to fix The action 'NAVIGATE' with payload?

提问人:MaxWell 提问时间:11/17/2023 最后编辑:halferMaxWell 更新时间:11/21/2023 访问量:32

问:

我正在使用 React Native 开发我的移动应用程序,但我遇到了导航问题。我首先开发了 HomeScreen、FormatioScreen、AddParticipantScreen 和 SummaryScreen。我最近开发了一个身份验证页面,仅向管理员提供对所有页面的访问。

另一方面,玩家应该只能访问 FormationScreen。导航在主屏幕和 app.js 上运行良好,但我不明白为什么它在我的 AuthScreen 上不起作用。我是一个初学者。

//AuthScreen.js
import React, { useState, useEffect, } from 'react';
import { View, Text, Button, TextInput, StyleSheet, TouchableOpacity } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { useFocusEffect } from '@react-navigation/native';
import { NavigationContainer } from '@react-navigation/native';


export default function AuthScreen({ setIsAdmin }) {
  const [password, setPassword] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const navigation = useNavigation();
  console.log('Navigation in AuthScreen:', navigation);


  const navigateToFormation = () => {
    navigation.navigate('Formation');
  };


  const handleAdminLogin = () => {
    if (password === 'test') {
      setIsAdmin(true);
      setIsAuthenticated(true);
    } else {
      alert('Mot de passe incorrect');
    }
  };

  const handlePlayerLogin = () => {
    setIsAdmin(false);
    setIsAuthenticated(true);
    console.log('After navigation to Formation');
  };
  
  useFocusEffect(
    React.useCallback(() => {
      if (isAuthenticated) {
        console.log('Navigating to Formation');
        // Déplacer la navigation à l'intérieur du useEffect
        const navigateToFormation = () => {
          navigation.navigate('Formation');
        };
        navigateToFormation();
      }
    }, [navigation, isAuthenticated])
  );
  
  
  return (
    <View style={styles.container}>
      <Text style={styles.title}>Page d'authentification</Text>
      <TextInput
        style={styles.input}
        placeholder="Mot de passe"
        secureTextEntry
        onChangeText={(text) => setPassword(text)}
      />
      <Button title="Se connecter en tant qu'admin" onPress={handleAdminLogin} />
      <Button title="Se connecter en tant que joueur" onPress={handlePlayerLogin} />
      <TouchableOpacity style={styles.button} onPress={navigateToFormation}>
          <Text style={styles.buttonText}>🏐 JOUEURS 🏐</Text>
        </TouchableOpacity>

    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  title: {
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 16,
  },
  input: {
    height: 40,
    borderColor: 'gray',
    borderWidth: 1,
    marginBottom: 16,
    padding: 8,
    width: '80%',
  },
});
//app.js
import React, { useState } from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { Provider } from 'react-redux';
import store from './store';
import HomeScreen from './screens/HomeScreen';
import FormationScreen from './screens/FormationScreen';
import SummaryScreen from './screens/SummaryScreen';
import AddParticipantsScreen from './screens/AddParticipantsScreen';
import AuthScreen from './screens/AuthScreen';

const Stack = createNativeStackNavigator();

export default function App() {
  const [isAdmin, setIsAdmin] = useState(false);
  const [isAuthenticated, setIsAuthenticated] = useState(false);


  return (
    <Provider store={store}>
      <NavigationContainer>
        <Stack.Navigator initialRouteName='Auth'>
          {isAdmin ?   (
            <>
              <Stack.Screen name="Accueil" component={HomeScreen} />
              <Stack.Screen name="Formation" component={FormationScreen} />
              <Stack.Screen name="Résumé" component={SummaryScreen} />
              <Stack.Screen
                name="Ajouter Participants"
                component={AddParticipantsScreen}
              />
            </>
          ) : (
            <Stack.Screen name="Auth">
              {(props) => <AuthScreen {...props} setIsAdmin={setIsAdmin} setIsAuthenticated={setIsAuthenticated} />}
            </Stack.Screen>
          )}
        </Stack.Navigator>
      </NavigationContainer>
    </Provider>
  );
}

PS:该应用程序不需要高级安全措施;它只是为了娱乐目的。代码中不会存储任何敏感数据。

我尝试了许多在这里和 React Native 嵌套导航文档中找到的东西,但我没有成功。

react-native 导航 react-navigation

评论


答:

0赞 user18309290 11/18/2023 #1

不要手动导航到有条件地呈现屏幕。对不同的角色使用单独的屏幕集。下面是一个简单的示例:

export default function App() {
  const [role, setRole] = useState(null);

  return (
    <NavigationContainer>
      <Stack.Navigator>
        {role == 'admin' ? (
          <>
            <Stack.Screen name="Admin" component={AdminScreen} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
            ...
          </>
        ) : role == 'player' ? (
          <>
            <Stack.Screen name="Player" component={PlayerScreen} />
            <Stack.Screen name="Settings" component={SettingsScreen} />
            ...
          </>
        ) : (
          <>
            <Stack.Screen
              name="SignIn"
              component={() => <SignInScreen setRole={setRole} />}
            />
          </>
        )}
      </Stack.Navigator>
    </NavigationContainer>
  );
}

有关详细信息,请参阅身份验证流