Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 反应导航+;用于检查身份验证/受保护路由的高阶组件(HOC)_Javascript_Reactjs_React Native_React Navigation_Higher Order Components - Fatal编程技术网

Javascript 反应导航+;用于检查身份验证/受保护路由的高阶组件(HOC)

Javascript 反应导航+;用于检查身份验证/受保护路由的高阶组件(HOC),javascript,reactjs,react-native,react-navigation,higher-order-components,Javascript,Reactjs,React Native,React Navigation,Higher Order Components,我遇到了一个问题,我正在使用高阶组件检查用户是否经过身份验证(checkAuth)。我的问题是,路由似乎受到保护,因为它不显示在屏幕上,但它确实加载了底部选项卡导航、标题,并且没有路由回登录屏幕 checkAuthTest只是我编写的一个函数,用于导航到对话屏幕: // Check Auth Test (Testing) checkAuthTest = () => { try { console.log('Navigating to App Stack')

我遇到了一个问题,我正在使用高阶组件检查用户是否经过身份验证(checkAuth)。我的问题是,路由似乎受到保护,因为它不显示在屏幕上,但它确实加载了底部选项卡导航、标题,并且没有路由回登录屏幕

checkAuthTest只是我编写的一个函数,用于导航到对话屏幕:

  // Check Auth Test (Testing)
  checkAuthTest = () => {
    try {
      console.log('Navigating to App Stack')
      console.log(`Current User: ${firebase.auth().currentUser}`);

      // this.props.navigation.navigate('AppStack');
      // this.props.navigation.navigate('AuthLoading');
      this.props.navigation.navigate('Conversations');
    }
    catch (error) {
      console.log(error);
    }
  };
export default connect(mapStateToProps, mapDispatchToProps)(checkAuth(Conversations));
高阶组件:

  // Check Auth Test (Testing)
  checkAuthTest = () => {
    try {
      console.log('Navigating to App Stack')
      console.log(`Current User: ${firebase.auth().currentUser}`);

      // this.props.navigation.navigate('AppStack');
      // this.props.navigation.navigate('AuthLoading');
      this.props.navigation.navigate('Conversations');
    }
    catch (error) {
      console.log(error);
    }
  };
export default connect(mapStateToProps, mapDispatchToProps)(checkAuth(Conversations));
如果用户经过身份验证,则高阶组件将用户路由到该组件。如果用户未通过身份验证,则高阶组件将用户路由回登录屏幕

// Imports: Dependencies
import React from 'react';
import firebase from 'firebase';

// Imports: Screens
import Login from '../../screens/auth-stack/Login';

// Higher Order Component: Check Auth
const CheckAuth = (OriginalComponent) => props => {
  class CheckAuth extends React.Component {    
    render() {
      // Check Authentication (Working)
      if (firebase.auth().currentUser !== null) {
        return <OriginalComponent {...this.props} />
      }
      // Redirect To Login (Not Working)
      else {
        return <Login />
      }
    }
  }

  // Return Check Auth Component
  return CheckAuth;
}

// Exports
export default CheckAuth;
登录组件

// Imports: Dependencies
import React, { Component } from 'react';
import { Button, SafeAreaView, StyleSheet, Text } from 'react-native';
import { connect } from 'react-redux';

// Imports: Redux Actions
import { 
  loginWithAppleRequest,
} from '../../redux/actions/authActions';

// TEST: Delete Later
import firebase from 'firebase';
import { appleAuth } from '../../firebase/firebase';

// Imports: Components
import FBLoginButton from '../../components/FacebookLoginButton';
import GoogleLoginButton from '../../components/GoogleLoginButton';
import SignOutButton from '../../components/SignOutButton';

// Screen: Login
class Login extends Component {
  constructor(props) {
    super(props);
  }

  // React Navigation: Options
  static navigationOptions = {
    headerStyle: {
      elevation: 0,
      shadowOpacity: 0,
      borderBottomWidth: 0,
    }
  };

  // Login With Apple
  loginWithApple = () => {
    try {
      firebase
      .auth()
      .signInWithPopup(appleAuth)
      .then((result) => {
        // The signed-in user info.
        let user = result.user;
        // You can also get the Apple OAuth Access and ID Tokens.
        let accessToken = result.credential.accessToken;
        let idToken = result.credential.idToken;

        console.log('User');
        console.log(user);

        console.log('Access Token');
        console.log(accessToken);

        console.log('ID Token');
        console.log(idToken);
      })
      .catch((error) => {
        // Handle Errors here.
        let errorCode = error.code;
        let errorMessage = error.message;
        // The email of the user's account used.
        let email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        let credential = error.credential;

        console.log('Error Code');
        console.log(errorCode);

        console.log('Error Message');
        console.log(errorMessage);

        console.log('Email');
        console.log(email);

        console.log('Credential');
        console.log(credential);
      });
    }
    catch (error) {
      console.log(error);
    }
  };

  // Check Auth Test (Testing)
  checkAuthTest = () => {
    try {
      console.log('Navigating to App Stack')
      console.log(`Current User: ${firebase.auth().currentUser}`);

      // this.props.navigation.navigate('AppStack');
      // this.props.navigation.navigate('AuthLoading');
      this.props.navigation.navigate('Conversations');
    }
    catch (error) {
      console.log(error);
    }
  };

  render() {
    return (
      <SafeAreaView style={styles.container}>        
        <GoogleLoginButton />
        <FBLoginButton />

        <Button onPress={this.checkAuthTest} title="Check Auth Test" />

        <SignOutButton />

      </SafeAreaView>
    )
  }
}

// Styles
const styles = StyleSheet.create({
  container: {
    height: '100%',
    display: 'flex',
    justifyContent: 'center',
    alignItems: 'center',
  },
});

// Map State To Props (Redux Store --> Component)
const mapStateToProps = (state) => {
  // Redux Store --> Component
  return {
    // uid: state.authReducer.uid,
  };
};

// Map Dispatch To Props (Dispatch Actions To Redux Store To Grab Data)
const mapDispatchToProps = (dispatch) => {
  // Action
  return {
    // Redux: Dispatch Login With Apple Action
    reduxLoginWithAppleRequest: () => dispatch(loginWithAppleRequest()),
  };
};

// Exports
export default connect(mapStateToProps, mapDispatchToProps)(Login);
//导入:依赖项
从“React”导入React,{Component};
从“react native”导入{按钮、SafeAreaView、样式表、文本};
从'react redux'导入{connect};
//导入:Redux操作
导入{
loginWithAppleRequest,
}来自“../../redux/actions/authActions”;
//测试:稍后删除
从“firebase”导入firebase;
从'../../firebase/firebase'导入{appleAuth};
//进口:组件
从“../../components/FacebookLoginButton”导入FBLoginButton;
从“../../components/GoogleLoginButton”导入GoogleLoginButton;
从“../../components/SignBurton”导入SignBurton;
//屏幕:登录
类登录扩展组件{
建造师(道具){
超级(道具);
}
//反应导航:选项
静态导航选项={
头型:{
海拔:0,
阴影不透明度:0,
边框底部宽度:0,
}
};
//使用Apple登录
登录苹果=()=>{
试一试{
火基
.auth()
.signInWithPopup(应用程序)
。然后((结果)=>{
//已登录的用户信息。
让user=result.user;
//您还可以获得Apple OAuth访问和ID令牌。
让accessToken=result.credential.accessToken;
让idToken=result.credential.idToken;
console.log('User');
console.log(用户);
log(“访问令牌”);
日志(accessToken);
log('ID Token');
console.log(idToken);
})
.catch((错误)=>{
//在这里处理错误。
设errorCode=error.code;
让errorMessage=error.message;
//使用的用户帐户的电子邮件。
让email=error.email;
//使用的firebase.auth.AuthCredential类型。
让凭证=error.credential;
console.log(“错误代码”);
控制台日志(错误代码);
console.log('Error Message');
控制台日志(错误消息);
console.log(“电子邮件”);
控制台日志(电子邮件);
console.log(“凭证”);
控制台日志(凭证);
});
}
捕获(错误){
console.log(错误);
}
};
//检查验证测试(测试)
checkAuthTest=()=>{
试一试{
console.log('导航到应用程序堆栈')
log(`Current User:${firebase.auth().currentUser}`);
//this.props.navigation.navigate('AppStack');
//this.props.navigation.navigate('AuthLoading');
this.props.navigation.navigate('Conversations');
}
捕获(错误){
console.log(错误);
}
};
render(){
返回(
)
}
}
//风格
const styles=StyleSheet.create({
容器:{
高度:“100%”,
显示:“flex”,
为内容辩护:“中心”,
对齐项目:“居中”,
},
});
//将状态映射到道具(Redux存储-->组件)
常量mapStateToProps=(状态)=>{
//Redux存储-->组件
返回{
//uid:state.authReducer.uid,
};
};
//将分派映射到道具(将操作分派到Redux存储以获取数据)
const mapDispatchToProps=(调度)=>{
//行动
返回{
//Redux:使用Apple操作发送登录
reduxLoginWithAppleRequest:()=>调度(loginWithAppleRequest()),
};
};
//出口
导出默认连接(mapStateToProps、mapDispatchToProps)(登录);

错误会告诉您出了什么问题。返回的是函数而不是元素:

constcheckauth=(OriginalComponent)=>props=>{
类CheckAuth扩展了React.Component{
// ...
}
//返回检查验证组件
返回CheckAuth;
}
现在,当您使用它时:

CheckAuth(对话)
结果:

const Component=props=>{
类CheckAuth扩展了React.Component{
// ...
}
//这是一个组件,但返回的是一个函数,而不是一个元素
返回CheckAuth;
}
您可能想要:

const CheckAuth=(原始组件)=>{
类CheckAuthComponent扩展了React.Component{
// ...
}
//返回检查验证组件
返回checkauth组件;
}

这里我删除了额外的
props=>
,因为您需要在这里返回组件(
CheckAuth
),而不是返回组件的函数(
props=>CheckAuth
)。

我认为这与如何导出登录组件有关,你可以添加这个代码,这样我就可以查看它了吗?只是添加了它作为登录屏幕的代码。谢谢你的关注!因此,它现在可以工作并导航到登录屏幕,但React Navigation的标题和选项卡导航器仍然存在。你知道那是什么吗?按下按钮时,它应该导航到对话屏幕(应用程序堆栈),但HOC返回登录屏幕(验证堆栈)。