【问题标题】:console.error:"the action navigate with payload...was not handled..."console.error:“使用有效负载导航的操作...未处理...”
【发布时间】:2020-09-19 22:08:40
【问题描述】:

我遇到了“LoginComponent”中的“onLogin”函数的问题。按下处理该功能的 TouchableOpacity 后,我希望用户被定向到“HomeComponent”,但我得到了这个 console.error:“使用有效负载导航的操作......未处理......”任何人都知道这是为什么?任何帮助将不胜感激。谢谢!

import React, { Component } from 'react';
import 'react-native-gesture-handler';
import { createStackNavigator } from '@react-navigation/stack';
import WelcomeScreen from './WelcomeComponent';
import LoginScreen from './LoginComponent';
import RegisterScreen from './RegisterComponent';
import HomeScreen from './HomeComponent';
import { NavigationContainer } from '@react-navigation/native';
import { createMaterialBottomTabNavigator } from '@react-navigation/material-bottom-tabs';
import { AsyncStorage } from 'react-native';

const AuthStack = createStackNavigator();
const AuthStackScreen = () => {
    return <AuthStack.Navigator initialRouteName="Welcome">
        <AuthStack.Screen name="Welcome" component={WelcomeScreen} />
        <AuthStack.Screen name="Login" component={LoginScreen} />
        <AuthStack.Screen name="Register" component={RegisterScreen} />
    </AuthStack.Navigator>
};

const HomeTab = createMaterialBottomTabNavigator();
const HomeTabScreen = () => {
    return <HomeTab.Navigator initialRouteName="Home">
        <HomeTab.Screen name="Home" component={HomeScreen} />
    </HomeTab.Navigator>
}

class Navigation extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isLoggedIn: false,
        };
        this.loginStatusCheck();
    }

    loginStatusCheck = async () => {
        const userToken = await AsyncStorage.getItem("userprofile");
        if(userToken) {
            this.setState({ isLoggedIn: true })
        } else {
            this.setState({ isLoggedIn: false })
        }
    }
    
    render() {
        return(
            <NavigationContainer>
                {this.state.isLoggedIn ? <AuthStackScreen /> : <HomeTabScreen />}
            </NavigationContainer>
        );
    };
};
export default Navigation;

import React, { Component } from 'react';
import { StyleSheet, SafeAreaView, ScrollView, View, TouchableOpacity, Text, Linking, AsyncStorage } from 'react-native';
import { Input, CheckBox } from 'react-native-elements';
import { FontAwesome } from '@expo/vector-icons';

class LoginScreen extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: "",
            password:"",
            token: "",
            remember: false
        };
        this.getData();
    };

    handleUsernameChange = username => {
        this.setState({ username })
    };

    handlePasswordChange = password => {
        this.setState({ password })
    };

    onLogin = async () => {
        try {
            await AsyncStorage.setItem("userprofile", JSON.stringify({ username: this.state.username, password: this.state.password }));
            this.props.navigation.navigate("Home", {
                screen: "HomeScreen",
            });
        } catch (err) {
            console.log(err);
        }
    };

    getData = async () => {
        try { 
            const userprofile = await AsyncStorage.getItem("userprofile");
            const userProfile = JSON.parse(userprofile);
            if (userProfile !== null) {
                this.setState({ ...userProfile })
            }
            if (username !== null) {
                this.setState({ username })
            }
            if (password !== null) {
            this.setState({ password })
            }
        } catch (err) {
            console.log(err);
        }
    }

    render() {
        const { username, password } = this.state;

        return (
            <SafeAreaView style={styles.container}>
                <ScrollView>
                    <Text style={styles.titleText}>Login</Text>
                    <Text style={styles.fillerText}>Hi there! Nice to see you again.</Text>
                    <Input 
                        inputStyle={{color: 'white'}}
                        placeholder="Enter username"
                        onChangeText={this.handleUsernameChange}
                        value={username}
                        keyboardType="email-address"
                        autoCapitalize="none"
                        leftIcon={{ type: 'font-awesome', name: 'user-circle-o', color: 'white', marginRight: 10 }}
                    />
                    <Input
                        inputStyle={{color: 'white'}}
                        placeholder="Password"
                        secureTextEntry
                        onChangeText={this.handlePasswordChange}
                        value={password}
                        leftIcon={{ type: 'font-awesome', name: 'lock', color: 'white', marginRight: 10 }}
                    />
                    <CheckBox 
                        title="Remember Me"
                        checked={this.state.remember}
                        onPress={() => this.setState({remember: !this.state.remember})}
                        containerStyle={styles.rememberCheckbox}
                        textStyle={{color: 'white'}}
                        checkedColor="crimson"
                    />
                    <TouchableOpacity 
                        style={styles.loginButton} 
                        title="Login" type="submit" 
                        onPress={this.onLogin}
                        >
                        <Text style={styles.buttonText}>Login</Text>
                    </TouchableOpacity>
                    <Text style={{textAlign: 'center', color: 'grey', marginTop: 20}}>
                        OR use an account from one of the following:
                    </Text>
                    <View style={styles.buttonsContainer}>
                        <TouchableOpacity style={styles.twitterButton}>
                            <FontAwesome name="twitter" color="white" style={{marginRight: 5}}/>
                            <Text style={{color: 'white'}}>Twitter</Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={styles.facebookButton}>
                            <FontAwesome name="facebook-square" color="white" style={{marginRight: 5}}/>
                            <Text style={{color: 'white'}}>Facebook</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={{alignItems: 'center'}}>
                    <TouchableOpacity style={styles.googleButton}>
                        <FontAwesome name="google" color="black" style={{marginRight: 5}}/>
                        <Text style={{color: 'grey'}}>Google</Text>
                        </TouchableOpacity>
                    </View>
                    <View style={styles.linkContainer}>
                        <TouchableOpacity style={{marginTop: 75}} onPress={() => Linking.openURL('#')}>
                            <Text style={{color: 'white'}}>
                                Forgot Your Password?
                            </Text>
                        </TouchableOpacity>
                        <TouchableOpacity style={{marginTop: 75, marginLeft: 210}} onPress={() => Linking.openURL('#')}>
                            <Text style={{color: 'white'}}>
                                Register
                            </Text>
                        </TouchableOpacity>
                    </View>
                </ScrollView>
            </SafeAreaView>
        );
    };
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        backgroundColor: 'black'
    },
    buttonsContainer: {
        flex: 2,
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: 'row'
    },
    linkContainer: {
        flex: 3,
        justifyContent: 'center',
        flexDirection: 'row'
    },
    titleText: {
        fontSize: 26,
        color: 'white',
        marginBottom: 30,
        marginTop: 20
    },  
    fillerText: {
        color: 'grey',
        marginBottom: 20
    },
    loginButton: {
        backgroundColor: 'crimson',
        paddingVertical: 17,
        paddingHorizontal: 25,
        borderRadius: 20,
        textAlign: 'center'
    },
    buttonText: {
        color: 'white',
        fontSize: 18,
        textAlign: 'center'
    },
    twitterButton: {
        backgroundColor: '#00acee',
        marginTop: 20,
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
        width: '40%',
        marginLeft: 20,
        flexDirection: 'row',
        borderRadius: 20
    },
    facebookButton: {
        backgroundColor: '#4267B2',
        marginTop: 20,
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
        width: '40%',
        marginLeft: 20,
        flexDirection: 'row',
        borderRadius: 20
    },
    googleButton: {
        backgroundColor: '#FFFFFF',
        marginTop: 20,
        padding: 10,
        justifyContent: 'center',
        alignItems: 'center',
        width: '40%',
        marginLeft: 20,
        flexDirection: 'row',
        borderRadius: 20
    },
    rememberCheckbox: {
        margin: 10,
        marginBottom: 20,
        backgroundColor: null
    }
});

export default LoginScreen;

【问题讨论】:

  • HomeTabScreen 函数应该在检查 this.state.isLoggedIn 是否为真后呈现。如果 this.state.isLoggedIn 为 false,则应该显示 AuthStackScreen 函数,这是身份验证之前的默认设置。我在 LoginComponent.js 和 NavigationComponent.js 中通过异步存储处理身份验证。这有助于澄清任何事情吗?
  • 我认为鉴于这种结构,navigate 是不必要的。重要的想法是确保Navigation 在您将用户数据设置在异步存储中后重新呈现。你说如果this.state.isLoggedInfalse,则应该显示AuthStack,但在你当前的代码中,情况正好相反。
  • 我是否可以在我的 NavigationComponent.js 中创建一个异步函数,该函数可以“重新加载”应用程序,以便对 this.state.isLoggedIn 进行布尔检查,因为我现在知道你在做什么说我不需要那个 navigation.navigate 道具?

标签: reactjs navigation native


【解决方案1】:

我认为没有必要在您的LoginScreen 组件中使用navigate,因为您已经编写了根据isLoggedIn 的值有条件地呈现两个导航器的代码。

您在当前实现中缺少的是一种从 LoginScreen 组件中更新 isLoggedIn 的方法。然后,如果 isLoggedIn 更新并设置为 trueNavigation 组件将被重新渲染,HomeScreen 组件无需导航即可显示。

我在这里选择使用react context,但如果您愿意,也可以将此方法与 redux 之类的方法一起使用。使用 react context 之类的原因是能够轻松地在组件之间传递isLoggedIn 及其设置器。

我将举一个更一般的例子,因为这样更容易说明方法:

// Imports and other stuff...

const LoginContext = React.createContext([null, () => {}]);

const LoginContextProvider = props => {
  const [isLoggedIn, setIsLoggedIn] = React.useState(false);
  return (
    <LoginContext.Provider value={[isLoggedIn, setIsLoggedIn]}>
      {props.children}
    </LoginContext.Provider>
  );
};

const HomeScreen = () => {
  return (
    <View>
      <Text>HomeScreen</Text>
    </View>
  );
};

const LoginScreen = () => {
  const [isLoggedIn, setIsLoggedIn] = React.useContext(LoginContext);
  return (
    <View>
      <Text>LoginScreen</Text>
      <Button
        title="login"
        onPress={() => {
          setIsLoggedIn(true);
        }}
      />
    </View>
  );
};

const HomeTabScreen = () => {
  return (
    <Tab.Navigator>
      <Tab.Screen name="Home" component={HomeScreen} />
    </Tab.Navigator>
  );
};

const AuthStackScreen = ({ navigation }) => {
  return (
    <Stack.Navigator>
      <Stack.Screen name="Login" component={LoginScreen} />
    </Stack.Navigator>
  );
};

const Navigation = () => {
  const [isLoggedIn, setIsLoggedIn] = React.useContext(LoginContext);
  return (
    <NavigationContainer>
      {isLoggedIn ? <HomeTabScreen /> : <AuthStackScreen />}
    </NavigationContainer>
  );
};

export default function App() {
  return (
    <LoginContextProvider>
      <Navigation />
    </LoginContextProvider>
  );
}

所以上面显示的方法是创建一个提供程序来保存您的isLoggedIn 状态和设置器 (setIsLoggedIn)。然后,当我们使用此提供程序包装Navigation 时,我们可以从提供程序内的任何组件访问isLoggedsetIsLoggedIn,从而允许我们更新LoginScreen 组件内的isLogged 状态。当此状态更新时,提供程序及其内部的所有内容(即Navigation)将重新渲染并显示HomeScreen 组件。


通常惯例是将大多数与 react 上下文相关的东西放在自己的文件中,并在需要的组件中导入部分,但出于演示目的,我没有这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多