在 ReactJs 中使用 Firebase 身份验证功能设置身份验证上下文的最简单方法是什么?
我想在我的 ReactJs 网站中设置 Firebase 身份验证,同时我想在其中使用 Context API。我应该为此应用什么正确的技术。
import { getAuth, onAuthStateChanged } from "firebase/auth";
import { useEffect, useState, createContext } from "react";
const AuthContext = React.createContext();
const auth = getAuth();
function AuthProvider({ children }) {
const [authUser, setAuthUser] = useState(undefined);
useEffect(() => {
return onAuthStateChanged(auth, user => setAuthUser(user));
}, []);
return <AuthContext.Provider value={authUser}>{children}</AuthContext.Provider>;
}
更多详细信息请参见这个答案。
使用 React 设置 Firebase 身份验证涉及几个步骤。以下是使用 Firebase JavaScript SDK 和 React Context 管理身份验证状态的基本设置:
创建一个AuthContext来管理身份验证状态:
import React, { createContext, useEffect, useState } from 'react';
import firebase from 'firebase/app';
import 'firebase/auth';
// Initialize Firebase with your config
firebase.initializeApp(firebaseConfig);
// Create AuthContext
export const AuthContext = createContext();
export const AuthProvider = ({ children }) => {
const [currentUser, setCurrentUser] = useState(null);
useEffect(() => {
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
setCurrentUser(user);
});
return () => {
unsubscribe();
};
}, []);
const signIn = async (email, password) => {
try {
await firebase.auth().signInWithEmailAndPassword(email, password);
} catch (error) {
console.error('Error signing in:', error);
}
};
const signOut = async () => {
try {
await firebase.auth().signOut();
} catch (error) {
console.error('Error signing out:', error);
}
};
const value = {
currentUser,
signIn,
signOut,
};
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
使用 AuthProvider 包装您的应用程序:
import React from 'react';
import { AuthProvider } from './AuthContext';
import YourApp from './YourApp'; // Replace this with your app component
const App = () => {
return (
<AuthProvider>
<YourApp />
</AuthProvider>
);
};
export default App;
在组件中使用 AuthContext:
import React, { useContext } from 'react';
import { AuthContext } from './AuthContext';
const YourComponent = () => {
const { currentUser, signIn, signOut } = useContext(AuthContext);
// Use currentUser, signIn, signOut as needed
return (
<div>
{currentUser ? (
<button onClick={signOut}>Sign Out</button>
) : (
<button onClick={() => signIn('email', 'password')}>Sign In</button>
)}
</div>
);
};
export default YourComponent;