首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >JS函数使用Firebase时出错并作出反应

JS函数使用Firebase时出错并作出反应
EN

Stack Overflow用户
提问于 2022-03-11 08:42:47
回答 1查看 27关注 0票数 0

谢谢你的耐心。我正在我的站点上实现Firebase,但是当我在FormUp.js中调用注册函数(在AuthContext.js中声明)时,它没有引用函数定义。这将导致在FormUp.js中调用函数,而不是调用在AuthContext.js中定义的自己的函数,而是落入catch分支(“未能创建帐户”)。我不明白为什么。希望有人能帮我,谢谢!错误:

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
TypeError: _firebase__WEBPACK_IMPORTED_MODULE_1__.auth.createUserWithEmailAndPassword is not a function
    at signup (bundle.js:4226:56)
    at handleSubmit (bundle.js:2575:13)
    at HTMLUnknownElement.callCallback (bundle.js:41062:18)
    at Object.invokeGuardedCallbackDev (bundle.js:41111:20)
    at invokeGuardedCallback (bundle.js:41171:35)
    at invokeGuardedCallbackAndCatchFirstError (bundle.js:41186:29)
    at executeDispatch (bundle.js:45421:7)
    at processDispatchQueueItemsInOrder (bundle.js:45453:11)
    at processDispatchQueue (bundle.js:45466:9)
    at dispatchEventsForPlugins (bundle.js:45477:7)

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
    at Navbar (http://localhost:3000/static/js/bundle.js:3361:76)
    at Home

代码:

AuthContext.js

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import React, { useContext, useState, useEffect } from "react";
import { auth } from "../firebase";
import { createUserWithEmailAndPassword } from "firebase/auth";

const AuthContext = React.createContext();

export function useAuth() {
  return useContext(AuthContext);
}

export function AuthProvider({ children }) {
  const [currentUser, setCurrentUser] = useState();
  const [loading, setLoading] = useState(true);

  function signup(email, password) {
    return auth.createUserWithEmailAndPassword(email, password);
  }

  function login(email, password) {
    return auth.signInWithEmailAndPassword(email, password);
  }

  function logout() {
    return auth.signOut();
  }

  function resetPassword(email) {
    return auth.sendPasswordResetEmail(email);
  }

  function updateEmail(email) {
    return currentUser.updateEmail(email);
  }

  function updatePassword(password) {
    return currentUser.updatePassword(password);
  }

  useEffect(() => {
    const unsubscribe = auth.onAuthStateChanged((user) => {
      setCurrentUser(user);
      setLoading(false);
    });

    return unsubscribe;
  }, []);

  const value = {
    currentUser,
    login,
    signup,
    logout,
    resetPassword,
    updateEmail,
    updatePassword,
  };

  return (
    <AuthContext.Provider value={value}>
      {!loading && children}
    </AuthContext.Provider>
  );
}

firebase.js

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";

const firebaseConfig = {
  //Hidden
};

const app = initializeApp(firebaseConfig);
const auth = getAuth();
export { app, auth };

FormUp.js

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
import React, { useRef, useState } from "react";
import { Link } from "react-router-dom";
import {
  FormUser,
  Input,
  Label,
  Subtitle,
  TextWrapper,
  TopLine,
  FormButton,
  Credentials,
  HomePage,
  SignInLink,
  SignInText,
  RedirectSignIn,
  Credential,
} from "./Form.elements";
import { FaAngleLeft } from "react-icons/fa";
import { useAuth } from "../../contexts/AuthContext";
import { Alert } from "bootstrap";

const FormUp = ({
  primary,
  lightBg,
  lightTopLine,
  lightTextDesc,
  buttonLabel,
  description,
  topLine,
}) => {
  const emailRef = useRef();
  const passwordRef = useRef();
  const passwordConfirmRef = useRef();
  const { signup } = useAuth();
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  async function handleSubmit(e) {
    e.preventDefault();

    if (passwordRef.current.value !== passwordConfirmRef.current.value) {
      return setError("Password do not match");
    }

    try {
      setError("");
      setLoading(true);
      await signup(emailRef.current.value, passwordRef.current.value);
    } catch {
      setError("Failed to create an account");
    }

    setLoading(false);
  }

  return (
    <>
      <style>
        @import
        url('https://fonts.googleapis.com/css2?family=Poppins:wght@100;200;300;400;500;600;700;800;900&display=swap');
      </style>
      <FormUser lightBg={lightBg} onSubmit={handleSubmit}>
        <TextWrapper>
          <HomePage href="/">
            <FaAngleLeft />
            <TopLine lightTopLine={lightTopLine}>{topLine}</TopLine>
          </HomePage>
          <Subtitle lightTextDesc={lightTextDesc}>{description}</Subtitle>
          {error && (
            <h5 style={{ color: "red", paddingBottom: "30px" }}>{error}</h5>
          )}
          <Credentials>
            <Credential id="email">
              <Label>Email</Label>
              <Input
                ref={emailRef}
                required
                type="email"
                placeholder="Email..."
              ></Input>
            </Credential>
            <Credential id="password">
              <Label>Password</Label>
              <Input
                ref={passwordRef}
                required
                type="password"
                placeholder="Password..."
              ></Input>
            </Credential>
            <Credential id="password-confirm">
              <Label>Password confirmation</Label>
              <Input
                ref={passwordConfirmRef}
                required
                type="password"
                placeholder="Password confirmation..."
              ></Input>
            </Credential>
          </Credentials>

          <FormButton disabled={loading} type="submit" big primary={primary}>
            {buttonLabel}
          </FormButton>

          <RedirectSignIn>
            <SignInText>Already have an account?</SignInText>
            <SignInLink href="/sign-in">Log in</SignInLink>
          </RedirectSignIn>
        </TextWrapper>
      </FormUser>
    </>
  );
};

export default FormUp;
EN

回答 1

Stack Overflow用户

发布于 2022-03-11 08:59:16

这里的问题是,正如错误消息所暗示的,auth没有一个名为createUserWithEmailAndPassword的属性。您正在搜索的不是auth的一部分。您的代码应该类似于

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
function signup(email, password) {
  return createUserWithEmailAndPassword(auth, email, password);
}

而不是

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
function signup(email, password) {
  return auth.createUserWithEmailAndPassword(email, password);
}

检查此选项(如果使用的是SDK的版本8,则需要使用不同的方法)

https://firebase.google.com/docs/auth/web/password-auth#create_a_password-based_account

我的建议是在您的项目中添加一个链接,以方便地捕捉这些问题。在这种情况下,由于没有使用createUserWithEmailAndPassword的导入,该问题将立即可见。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71441847

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文