在本机反应中反应导航,具有条件堆栈和身份验证 [英] react navigation in react native, with conditional stack, and authentication

查看:81
本文介绍了在本机反应中反应导航,具有条件堆栈和身份验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

import React, { Component } from 'react'
import { Container, Content, Form, Item, Input, Label, Button,Text, Icon} from 'native-base'
import AsyncStorage from '@react-native-community/async-storage';
import authStore from '../store/authStore';
export default class Login extends Component {
    constructor(props){
        super(props);
        this.state={
            email:'',
            password:''
        }
    }
    handleLogin = async () =>{
        let requestObject = {
            email: this.state.email,
            password: this.state.password
        }
        authStore.userLogin(requestObject, response => {
            this.storeUserData(response.data.data);
            this.props.navigation.navigate('Home');
        })
    }
    storeUserData = async (value) => {
        try {
          const jsonValue = JSON.stringify(value)
          await AsyncStorage.setItem('@userData', jsonValue)
        } catch (e) {
          console.log(e);
        }
    }
    render() {
        return (
            <Container>
                <Content contentContainerStyle={{flex: 1, justifyContent:'center'}}>
                <Form style={{margin:10}}>
                    <Item rounded last style={{margin:10}}>
                    <Icon active type="FontAwesome" name='user' />
                    <Input placeholder='User Name' 
                    onChangeText={(email)=>this.setState({email})} 
                    value={this.state.email}/>
                    </Item>
                    <Item rounded last style={{margin:10}}>
                    <Icon active type="FontAwesome" name='key' />
                    <Input placeholder='Password'
                    secureTextEntry
                    onChangeText={(password)=>this.setState({password})} 
                    value={this.state.password}/>
                    </Item>
                    <Button rounded block style={{margin:10}} onPress={() => this.handleLogin()}>
                    <Text>Sign-In</Text>
                    </Button>
                </Form>
                </Content>
            </Container>
        )
    }
}

const AuthStack = createStackNavigator();
AuthStackScreen = () =>
      <AuthStack.Navigator>
        <AuthStack.Screen name="Login" component={Login} />
      </AuthStack.Navigator>
HomeStackScreen = () =>
  <HomeStackDrawer.Navigator>
    <HomeStackDrawer.Screen name="Home" component={HomeScreen}/>
    <HomeStackDrawer.Screen name="Form" component={FormScreen}/>
    <HomeStackDrawer.Screen name="Logout" component={Logout}/>
  </HomeStackDrawer.Navigator>
export default class App extends Component{
  constructor(props){
    super(props);
    this.state={
      isloggedIn:false
    }
    this.loginStatusCheck();
  }
  loginStatusCheck = async () =>{
    const userToken = await AsyncStorage.getItem('@accessToken');
    if (userToken) {
      this.setState({isloggedIn:true})
    } else {
      this.setState({isloggedIn:false})
    }
  }
  render(){
    return(
      <NavigationContainer>
        {this.state.isloggedIn ? <HomeStackScreen/> : <AuthStackScreen/>}
      </NavigationContainer>
    )
  }
}

这是我的 App.js,我正在检查用户是否登录,然后相应地加载导航堆栈.我知道这个问题,如果我退出,我想导航到登录组件,但是 this.props.navigation.navigate('Login') 给出错误.因为我没有返回 Login 路线.如何解决这个问题?另外,当我 Login 出现同样的问题时,因为 Login 不在堆栈中.提前致谢

This is my App.js, I am checking if the user is logged in or not, then loading the Navigation stack accordingly. I know the problem, If I Logout, I want to navigate to the sign-in component, but this.props.navigation.navigate('Login') gives error. because I am not returning the Login route. How to solve this issue? Also, when I Log in same issue, as the Login is not present in the stack. Thank you in advance

包含登录组件

推荐答案

您必须进行一些更改才能解决此问题.您的问题是您试图访问导航堆栈中不存在的屏幕.而最大的问题是在 App.js 中使用状态变量来处理导航堆栈的切换.您可以通过在应用程序的上下文中维护登录状态来解决此问题.您也可以从其他屏幕更新它.更新登录状态后,您不必担心导航,您在 App.js 中的条件将为您管理.

You will have to do some changes to fix this issue. Your problem is you are trying to access a screen in a navigation stack which is not there. And the biggest problem is using a state variable in App.js to handle the switch of navigation stacks. You can resolve this by maintaining the login status in a context in your application. You can update it from other screens as well. Once you update the login status you dont have to worry about the navigation and your condition in the App.js will manage that for you.

代码应该如下所示.我提供了一个示例 Login 组件,它将更新上下文.您将不得不切换到功能组件.从您的代码中,我看不出这样做有任何问题.

The code should be something like below. I have given a sample Login component which will update the context. You will have to switch to functional component. From your code i dont see any problem of doing that.

const AppContext = createContext({
  isloggedIn: {},
  setLoggedIn: () => {},
});

const Login = () => {
  const { setLoggedIn } = useContext(AppContext);

  return (
    <View>
      <Button onPress={() => setLoggedIn(true)} />
    </View>
  );
};

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isloggedIn: false,
      loading: true,
    };
    this.loginStatusCheck();
  }

  setLoggedIn = value => {
    this.setState({ isloggedIn: value });
  };

  loginStatusCheck = async () => {
    const userToken = await AsyncStorage.getItem('@accessToken');
    if (userToken) {
      this.setState({ isloggedIn: true, loading: false });
    } else {
      this.setState({ isloggedIn: false, loading: false });
    }
  };

  render() {
    if (this.state.loading) return <ActivityIndicator />;

    return (
      <AppContext.Provider
        value={{
          isloggedIn: this.state.isloggedIn,
          setLoggedIn: this.setLoggedIn,
        }}>
        <NavigationContainer>
          {this.state.isloggedIn ? <HomeStackScreen /> : <AuthStackScreen />}
        </NavigationContainer>
      </AppContext.Provider>
    );
  }
}

希望这会有所帮助.

这篇关于在本机反应中反应导航,具有条件堆栈和身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆