反应本地Firebase身份验证

时间:2018-09-19 04:39:57

标签: firebase react-native firebase-authentication

在与firebase进行本地响应时,我得到了一个聊天应用程序代码。它使用一个按钮来显示我的注册朋友,但是我想检查此按钮单击用户何时登录。

这是渲染功能中的按钮代码

  render() {
    return (
      <View style={styles.containerl}>
        <StatusBar barStyle="light-content" backgroundColor="red" />
        <TouchableOpacity>
          <Text
            style={styles.buttonStyle}
            onPress={() => this.props.navigation.navigate("Friendlist")}
          >
            SHOW FRIEND LIST
          </Text>
        </TouchableOpacity>       
      </View>
    );
  }

我想将此Firebase身份验证代码添加到按“显示朋友列表”文本中。

firebase.auth().onAuthStateChanged((user) => {
      if (user) {
        console.log('user logged')
      }
   });

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:0)

您可以按照以下方式进行操作。添加标志以检查用户是否登录

    state = {
  isUserLogged: false
}

constructor(props) {
  super(props);

  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.setState({
        isUserLogged: true
      })
    } else {
      this.setState({
        isUserLogged: false
      })
    }
  });
}

render() {

  return (
    <View style={styles.containerl}>
      <StatusBar barStyle="light-content" backgroundColor="red" />
      <TouchableOpacity>
        <Text
          style={styles.buttonStyle}
          onPress={() => {
            if (this.state.isUserLogged) {
              this.props.navigation.navigate("Friendlist")
            } else {
              console.log('user not logged')
            }
          }
          }
        >
          SHOW FRIEND LIST
        </Text>
      </TouchableOpacity>
    </View>
  );
}

答案 1 :(得分:0)

为了显示用户是否已登录,您需要将变量附加到用户状态。因此,您的验证码:

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    console.log('user logged')
  }
 });

本质上,会将此方法放入constructor()componentDidMount()方法中。

从那里,您需要设置状态,例如-

firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    this.setState({ userLoggedIn: true });
    console.log('user logged')
  }
 });

,并且可以在您的render()中,通过this.state.userLoggedIn方法将条件附加到onPress()

如果您需要将登录状态发送到<Friendlist/>组件,则需要执行-

this.props.navigation.navigate("Friendlist", {userLoggedIn: this.state.userLoggedIn})

,并且在您的<Friendlist/>组件中,您可以从this.props.navigation.state.params.userLoggedIn

获取它