为什么我无法通过 firebase 获得身份验证?

Why cant I get authenticated by firebase?

我正在 react-redux 中与 redux-thunk 一起做一个项目(w hooks)。到了我想使用某种帐户身份验证的地步。我选择使用 Firebase,因为它很受欢迎。 所以我开始在 yt 上关注忍者的过时课程。知道这一点后,我正在检查 firebase 的文档,了解如何使用 redux-thunk 进行身份验证。 现在我要说的是,当我尝试登录我的 firebase 时,出现以下错误: “Firebase 实例尚不存在。请检查您的撰写功能。”

此处描述了类似的问题,但这很容易(当然...): SO LINK

我只能假设,问题出在我的 store.js 撰写函数的某处。只是,我按照书做了所有事情(或者至少我是这么认为的):http://docs.react-redux-firebase.com/history/v3.0.0/docs/getting_started.html 似乎没有任何帮助。

也许有新鲜感的人可以检查我的代码并告诉我,我在哪里做错了。

因为我认为错误在 store.js 中,所以我将从它开始:


store.js:

import { createStore, applyMiddleware} from 'redux';
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from 'redux-thunk';

import { getFirebase } from 'react-redux-firebase';
// import { getFirestore, reduxFirestore } from "redux-firestore";

import rootReducer from './reducers/rootReducer';

const middlewares = [
    thunk.withExtraArgument({getFirebase})
  ];

const store = createStore(rootReducer, composeWithDevTools(applyMiddleware(...middlewares)));

export default store;

fbConfig.js

const fbConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.REACT_APP_FIREBASE_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
  measurementId: process.env.REACT_APP_FIREBASE_MEASUREMENT_ID
  };

export default fbConfig;

我将上述文件导入我的 index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { BrowserRouter } from "react-router-dom";

import store from './store';
import App from './components/App/App';

import firebase from "firebase/app";
import "firebase/auth"

import fbConfig from "./config/fbConfig";

// import { createFirestoreInstance } from "redux-firestore";
import { ReactReduxFirebaseProvider } from 'react-redux-firebase';

import registerServiceWorker from "./registerServiceWorker";

console.log(fbConfig);
firebase.initializeApp(fbConfig);

//rrf stores authenticated users' data in Cloud Firestore
const rrfConfig = {
  userProfile: "users",
  // useFirestoreForProfile: true,
}

const rrfProps = {
  firebase,
  config: rrfConfig,
  dispatch: store.dispatch,
  // createFirestoreInstance
}

ReactDOM.render(
  <BrowserRouter>
    <Provider store={store} >
      <ReactReduxFirebaseProvider {...rrfProps} >
        <App />
      </ReactReduxFirebaseProvider>
    </Provider>
  </BrowserRouter>,
  document.querySelector("#root")
);

registerServiceWorker();

rootReducer.js 在这里我也有一个问题,因为当我在互联网上查看时,很多人只有一个文件,它正在处理名为 auth 的身份验证请求(登录,注销或注册)(至少在根目录中) reducer,比如 auth: authReducer)。我已将我的逻辑分成 3 个单独的文件。现在我想知道,如果我能做到这一点,还是我也应该有一个 auth reducer?

import { combineReducers } from 'redux';
import { firebaseReducer } from "react-redux-firebase";

import SigninReducer from "./auth/signinReducer";
import SignoutReducer from "./auth/signoutReducer";
import SignupReducer from "./auth/signupReducer";

const rootReducer = combineReducers({
    firebase: firebaseReducer,

    signin: SigninReducer,
    signout: SignoutReducer,
    signup: SignupReducer
});

export default rootReducer;

signinReducer.js

import { GET_SIGNIN_SUCCESS, GET_SIGNIN_ERROR } from "../../actions/index";

const DefaultState = {
    authMsg: ""
};

const SigninReducer = (state = DefaultState, action) => {
    switch (action.type) {
        case GET_SIGNIN_ERROR:
            console.log("login failed");
            return {
                ...state,
                authMsg: "Unable to login"
            };
        case GET_SIGNIN_SUCCESS:
            console.log("login success");
            return {
                ...state,
                authMsg: "login success"
            };
    default:
        return state
    }
}

export default SigninReducer;

action/getSignin.js

import { GET_SIGNIN_ERROR, GET_SIGNIN_SUCCESS } from "../index";

export const getSignin = (credentials) => async (dispatch, getState, {getFirebase}) => {
    console.log(credentials);
    const firebase = getFirebase();
    console.log(firebase);
    try {
        await firebase()
            .auth()
            .signInWithEmailAndPassword(credentials.email, credentials.password)
            .then(() => {
                dispatch({
                    type: GET_SIGNIN_SUCCESS
                });
            })
            .catch((error) => {
                dispatch({
                    type: GET_SIGNIN_ERROR,
                    error
                });
            });
        
    } catch(e) {
        dispatch ({
            type: GET_SIGNIN_ERROR,
            payload: "Invalid login credentials."
        });
    }
};

component/userSignin.js

import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { Link } from "react-router-dom";
import { getSignin } from "../../actions/auth/getSignin";

const UserSign = () => {
    const dispatch = useDispatch();

    const [ userStatus, setUserStatus ] = useState ({
        email: "",
        password: ""
    })

    const handleSubmit = (event) => {
        dispatch(getSignin(userStatus));
        event.preventDefault();
    }

    const handleChange = (event) => {
        const { id, value } = event.target;
        setUserStatus({
                ...userStatus,
                [id]: value
        })
    }

    const showLogin = () => {
        return (
            <div>
                <h4>Login</h4>
                <form onSubmit={handleSubmit}>
                    <div>
                        <label htmlFor="email">Email address</label>
                        <input type="email" id="email" onChange={handleChange} required />
                    </div>
                    <div>
                        <label htmlFor="password">Your Password</label>
                        <input type="password" id="password" onChange={handleChange} required />
                    </div>
                    <button>Login</button>
                </form>
            </div>
        )
    }

    return (
        <div>
            {showLogin()}
            <Link to={"/signup"}><p>SignUp</p></Link>
            <Link to={"/"}>Back</Link>
        </div>
    )
}

export default UserSign;

当我检查 console.log(fbConfig) 时,我看到我初始化了那个 firebase 配置(API_KEY,等等)。 同样在我的 action/getSignin.js 文件中,我可以 console.log 我的登录名和密码并检查它们是否已传递到那里。但是我得到一个错误,因为我的 API_KEY 不见了。

我用 Firebase 给出的值仔细检查了 API_KEY 值,它们确实匹配。

我没主意了。请帮忙

我明白了。

我的 API_KEY 值等存储在我的 .env.local 文件中。事实证明,如果我将它们直接写在 fbConfig 文件中,那么一切正常。 想知道为什么,因为在我以前的应用程序中我做了完全相同的事情并且它有效。我也可以 console.log 从我的 index.js 中的 .env.local 文件中提取值。但不知何故,他们没有得到初始化。

嗯,现在一切正常。