需要使用我的代码的 React-native 导航和身份验证屏幕的帮助

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

我正在尝试制作一个新的react-native应用程序,并且我想为此应用程序制作一个登录屏幕,但不幸的是我无法将登录屏幕切换到配置文件屏幕,该屏幕应该根据API的响应进行定向。我知道我的代码很复杂,但你认为我做错了什么以及如何修复它?

我得到的错误是这样的:任何导航器都没有处理带有有效负载{“name”:“ProfileScreen”,“params”的操作“NAVIGATE”。

您有一个名为“ProfileScreen”的屏幕吗?

如果您尝试导航到嵌套导航器中的屏幕,请参阅 https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator

这是我的 App.js 和 LoginScreen.js:

import React, { useEffect, useState } from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { createBottomTabNavigator } from '@react-navigation/bottom-tabs';
import { createStackNavigator } from '@react-navigation/stack';
import { NavigationContainer } from '@react-navigation/native';
import GamesScreen from './GamesScreen';
import ProfileScreen from './ProfileScreen';
import AddProfileScreen from './AddProfileScreen';
import RoomsPage from './RoomsPage';
import LoginScreen from './LoginScreen';
import Icon from 'react-native-vector-icons/FontAwesome';

const Tab = createBottomTabNavigator();
const Stack = createStackNavigator();

const GamesStack = ({ games }) => {
  return (
    <Stack.Navigator>
      <Stack.Screen
        name="  "
        options={{
          
        }}
      >
        {() => <GamesScreen games={games} />}
      </Stack.Screen>
      <Stack.Screen name="RoomsPage" component={RoomsPage} options={{ title: 'Rooms' }} />
    </Stack.Navigator>
  );
};


const App = () => {
  const [games, setGames] = useState([]);
  const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxLCJwYXNzd29yZF90aW1lc3RhbXAiOjE3MDMyNjc4MTAuMjAzNTE1LCJleHAiOjE3MDM3OTE5NDEsInRva2VuX3R5cGUiOiJhY2Nlc3MifQ.Xpncpl-LTAzeT9oeh-k6cBJTHkzS3E6tQIGvLmOVAR8';

  useEffect(() => {
    const apiUrl = 'http://192.168.144.49:8000/games/';

    fetch(apiUrl, {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    })
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
      })
      .then(apiData => {
        console.log('API Data:', apiData);
        setGames(apiData.games);
      })
      .catch(error => {
        console.error('Error fetching data:', error.message);
      });
  }, []);

  return (
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName="Login"
        tabBarOptions={{
          showLabel: false,
          style: {
            position: 'absolute',
            bottom: 25,
            left: 20,
            right: 20,
            elevation: 0,
            backgroundColor: '#ffffff', // Adjust the background color as needed
            borderRadius: 15,
            height: 90,
            ...styles.shadow, // Add shadow styling (defined below)
          },
          tabStyle: {
            justifyContent: 'center',
            alignItems: 'center',
          },
          iconStyle: {
            justifyContent: 'center',
            alignItems: 'center',
          },
        }}
      >
        <Tab.Screen
          name="Login"
          component={LoginScreen}
          options={{
            tabBarButton: () => null, 
          }} />
        <Tab.Screen
  name="Profile"
  component={ProfileScreen}
  options={{
    tabBarIcon: ({ color, size }) => (
      <Icon name="user" size={30} color={color} />
    ),
            
            headerTitle: () => (
              <Text style={{ fontSize: 30, fontWeight: 'bold', color: '#000000' }}>
                Profile
              </Text>
            ),
            headerTitleAlign: 'center',
            headerStyle: {
              backgroundColor: '#fff', // Adjust the background color as needed
            },
          }}
        />
        <Tab.Screen
          name="GamesList"
          options={{
            tabBarIcon: ({ color, size }) => (
              <Icon name="gamepad" size={30} color={color} />
            ),
            headerTitle: () => (
              <Text style={{ fontSize: 30, fontWeight: 'bold', color: '#000000' }}>
                Games
              </Text>
            ),
            headerTitleAlign: 'center',
            headerStyle: {
              backgroundColor: '#fff', // Adjust the background color as needed
            },
          }}
        >
          {() => <GamesStack games={games} />}
        </Tab.Screen>
        <Tab.Screen
          name="AddProfileScreen"
          component={AddProfileScreen}
          options={{
            tabBarButton: () => null, 
          }} 
          />
      </Tab.Navigator> 
    </NavigationContainer>
  );
};

const styles = {
  shadow: {
    shadowColor: '#7f5df0',
    shadowOffset: {
      width: 0,
      height: 10,
    },
    shadowOpacity: 0.25,
    shadowRadius: 3.5,
    elevation: 5,
  },
};

export default App;

import React, { useState } from 'react';
import { View, Text, TextInput, Button, Alert } from 'react-native';
import { useNavigation } from '@react-navigation/native';
import ProfileScreen from './ProfileScreen';

const LoginScreen = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigation = useNavigation();

  const handleLogin = async () => {
    try {
      const response = await fetch('http://192.168.144.49:8000/auth/token', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username,
          password,
        }),
      });

      if (response.ok) {
        const { access_token } = await response.json();
        // Navigating to the ProfileScreen with the token
        navigation.navigate('ProfileScreen', { token: access_token });
      } else {
        Alert.alert('Hata', 'Kullanıcı adı veya şifre yanlış.');
      }
    } catch (error) {
      console.error('Login Error:', error);
      Alert.alert('Hata', 'Bir hata oluştu, lütfen tekrar deneyin.');
    }
  };

  const handleRegister = () => {
    navigation.navigate('RegisterScreen');
  };
    

  return (
    <View>
      <Text>Kullanıcı Adı</Text>
      <TextInput
        value={username}
        onChangeText={(text) => setUsername(text)}
        placeholder="Username"
      />

      <Text>Şifre</Text>
      <TextInput
        value={password}
        onChangeText={(text) => setPassword(text)}
        secureTextEntry
        placeholder="Password"
      />

      <Button title="Giriş Yap" onPress={handleLogin} />
      <Button title="Kayıt Ol" onPress={handleRegister} />
    </View>
  );
};

export default LoginScreen;

reactjs react-native navigation httprequest
1个回答
0
投票

屏幕名称为“Profile”而不是“ProfileScreen”。因此,您应该导航到“个人资料”。

尝试在 LoginScreen.js 中将

navigation.navigate('ProfileScreen', { token: access_token });
更改为
navigation.navigate('Profile', { token: access_token });
,看看是否可以解决问题。

© www.soinside.com 2019 - 2024. All rights reserved.