首页 > 解决方案 > Firebase 身份验证不适用于 React

问题描述

我有一个使用 React 和 Firebase(Cloud Firestore & Authentication)的简单应用程序。我使用了 Firebase 身份验证登录/使用电子邮件和密码注册,但承诺没有响应,尽管它昨晚运行良好,并且 firebase.auth().onStateAuthChanged 也不起作用,但 firebase.auth().sendPasswordResetEmail()效果很好。我不知道有什么问题?

您可以在以下位置查看我的代码:https : //lfddm.csb.app/(我使用过代码框)

Firebase Cloud Firestore 规则:

match /users/{userId} {
    allow create: if request.auth.uid != null
  allow read, write: if request.auth.uid == userId
}

登录组件:

import React, { useState } from "react";
import { Link } from "react-router-dom";

import {
  Button,
  Modal,
  ModalHeader,
  ModalBody,
  Form,
  FormGroup,
  Label,
  Input
} from "reactstrap";

import firebase from "../config/firebase";

export default function SignInModal(props) {
  const [modal, setModal] = useState(false);
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const resetModal = () => {
    setModal(false);
    setEmail("");
    setPassword("");
  };

  const signIn = (e, p) => {
    // console.log(e, p);
    firebase
      .auth()
      .signInWithEmailAndPassword(e, p)
      .then(() => alert("Sign in successfully!"))
      .then(() => resetModal())
      .catch(err => alert(err.message));
  };

  const styles = {
    signModal: {
      display: "inline",
      margin: "0 3px"
    }
  };

  return (
    <div className="SignModal" style={styles.signModal}>
      <Button color="primary" onClick={() => setModal(!modal)}>
        Sign In
      </Button>
      <Modal isOpen={modal} toggle={() => resetModal()}>
        <ModalHeader toggle={() => resetModal()}>Sign In</ModalHeader>
        <ModalBody>
          <Form
            onSubmit={e => {
              e.preventDefault();
              signIn(email, password);
            }}
          >
            <FormGroup>
              <Label for="email">Email</Label>
              <Input
                type="email"
                id="email"
                value={email}
                onChange={e => setEmail(e.target.value)}
                required
              />
            </FormGroup>
            <FormGroup>
              <Label for="password">Password</Label>
              <Input
                type="password"
                id="password"
                value={password}
                onChange={e => setPassword(e.target.value)}
                required
              />
            </FormGroup>
            <Button
              type="submit"
              color="primary"
              style={{ marginRight: "5px" }}
            >
              Sign In
            </Button>
            <Link to="/forget-password">Forget password</Link>
          </Form>
        </ModalBody>
      </Modal>
    </div>
  );
}

signIn 函数不返回任何内容,这意味着 firebase.auth() 承诺正在等待处理。

标签: reactjsfirebaseauthenticationgoogle-cloud-firestore

解决方案


推荐阅读