簡體   English   中英

Navigation.navigate 在反應導航中不起作用

[英]Navigation.navigate does not work in react navigation

我正在創建一個應用程序並想創建一個用戶身份驗證頁面。 我按照反應導航網站的身份驗證流程頁面上的教程進行操作,但是現在每當我嘗試從登錄屏幕導航到注冊頁面時,都會收到警告“無法從不同組件的函數體內更新組件”。

這是我的 App.js:

import React, { useState } from 'react';
import {
    FlatList,
} from 'react-native';
import { NavigationContainer, useNavigation } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
import LoginScreen from "./Login";
import Home from "./Home";
import Signup from "./Signup";
import { AsyncStorage } from 'react-native'

export const COMPANY_NAME = "myCompany";

export const AuthContext = React.createContext();

const App: () => React$Node = () => {
    const [state, dispatch] = React.useReducer(
        (prevState, action) => {
            switch (action.type) {
                case 'RESTORE_TOKEN':
                    return {
                        ...prevState,
                        userToken: action.token,
                        isLoading: false,
                    };
                case 'SIGN_IN':
                    return {
                        ...prevState,
                        isSignout: false,
                        userToken: action.token,
                    };
                case 'SIGN_OUT':
                    return {
                        ...prevState,
                        isSignout: true,
                        userToken: null,
                    };
            }
        },
        {
            isLoading: true,
            isSignout: false,
            userToken: null,
        }
    );

    const authContext = React.useMemo(
        () => ({
            signIn: async data => {
                // In a production app, we need to send some data (usually username, password) to server and get a token
                // We will also need to handle errors if sign in failed
                // After getting token, we need to persist the token using `AsyncStorage`
                // In the example, we'll use a dummy token

                dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
            },
            signOut: () => dispatch({ type: 'SIGN_OUT' }),
            signUp: async data => {
                // In a production app, we need to send user data to server and get a token
                // We will also need to handle errors if sign up failed
                // After getting token, we need to persist the token using `AsyncStorage`
                // In the example, we'll use a dummy token

                dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' });
            },
        }),
        []
    );

    React.useEffect(() => {
        // Fetch the token from storage then navigate to our appropriate place
        const bootstrapAsync = async () => {
            let userToken;

            try {
                userToken = await AsyncStorage.getItem('userToken');
            } catch (e) {
                // Restoring token failed
            }

            // After restoring token, we may need to validate it in production apps

            // This will switch to the App screen or Auth screen and this loading
            // screen will be unmounted and thrown away.
            dispatch({ type: 'RESTORE_TOKEN', token: userToken });
        };

        bootstrapAsync();
    }, []);


    return (
        <NavigationContainer>
        <AuthContext.Provider value={{authContext}}>
        <RootStack state={state} authContext={authContext}/>
        </AuthContext.Provider>
        </NavigationContainer>
    );
};



function RootStack(props) {
    const Stack = createStackNavigator();


    return (

            <Stack.Navigator screenOptions={{ headerShown: false }}>
                {props.state.userToken == null ? (
                    <>
                        <Stack.Screen
                            name="Login"
                            component={LoginScreen}
                        />
                        <Stack.Screen
                            name="Signup"
                            component={Signup}
                        />
                    </>
                ) : (
                    <Stack.Screen
                        name="Home"
                        component={Home}
                    />
                )
                }
            </Stack.Navigator>

    );
}

這是我的 Login.js:

import {StatusBar, Text, TextInput, TouchableOpacity, View, Button, TouchableHighlight} from "react-native";
import styles, {MAIN_COLOR} from "./Styles";
import React, {useState} from "react";
import { COMPANY_NAME, AuthContext } from "./App";
import { useNavigation } from '@react-navigation/native'
import TouchableItem from "@react-navigation/stack/src/views/TouchableItem";

export default function LoginScreen({ navigation }) {
    //Must be a child of AuthContext.Provider
    const [username, setUsername] = useState();
    const [password, setPassword] = useState();

    const { authContext } = React.useContext(AuthContext);
    console.log(AuthContext)


    return (
        <View style={styles.container}>
            <StatusBar
                backgroundColor={MAIN_COLOR}
            />
            <Text style={styles.welcome}>Welcome to {COMPANY_NAME}!</Text>
            <TextInput
                style={styles.input}
                placeholder='Username'
                onChange={(text) => setUsername(text)}
            />
            <TextInput
                style={styles.input}
                placeholder='Password'
                secureTextEntry
                onChange={(text) => setPassword(text)}
            />
            <View style={styles.btnContainer}>
                <TouchableOpacity style={styles.usrBtn}
                                  onPress={() => navigation.navigate('Signup')}>
                    <Text style={styles.btnText}>Sign Up</Text>
                </TouchableOpacity>
                <TouchableOpacity style={styles.usrBtn}
                                  onPress={() => authContext.signIn({username, password})}>
                    <Text style={styles.btnText}>Login</Text>
                </TouchableOpacity>
            </View>
        </View>
    );
}

找到了答案。 在我的 Signup.js 中,我有一個像

<TouchableOpacity style={styles.usrBtn}
                                  onPress={navigation.navigate('Login')}>

那需要改為

<TouchableOpacity style={styles.usrBtn}
                                  onPress={() => navigation.navigate('Login')}>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM