從「react」匯入 React, { useState }; 從“../Services/FirebaseAuthService”導入FirebaseAuthService; const FirebaseAuth = React.createContext({ 使用者:空, 加載:真實, 角色:“”, 電子郵件:“”, 名字:“”, 是否活躍:假, 姓氏:“”, 位置:“”, 用戶ID:“”, }); 匯出 const FirebaseAuthProvider = ({ 兒童 }) => { const [用戶,setUser] = useState(null); const [角色,setRole] = useState(null); const [電子郵件,setEmail] = useState(“”); const [firstName, setFirstName] = useState(""); const [isActive, setIsActive] = useState(false); const [lastName, setLastName] = useState(“”); const [位置,setLocation] = useState(“”); const [userID, setUserID] = useState(“”); const [正在加載,setLoading] = useState(true); FirebaseAuthService.subscribeToAuthChanges( 設定用戶, 設定加載, 設定角色, 設定郵箱, 設定名字, 設定為活動狀態, 設定姓氏, 設定位置, 設定用戶ID ); 返回 ( <FirebaseAuth.Provider 值={{ 用戶, 載入中, 角色, 電子郵件, 名, 姓, 活躍, 地點, 使用者身份, }} > {孩子} </FirebaseAuth.Provider> ); }; 導出預設 FirebaseAuth; </前> <p>在這個例子中,我缺少一個查詢字串讀寫的設定函數,然而,以任何方式查詢該數組都會導致onAuthStateChanged()不斷循環,反覆向Firebase發出讀取請求。 <p>有沒有讀取解決方案但無法解決這個問題?</p> <p>我嘗試透過循環進行備份來避免遇到這個問題,但是,以任何方式查詢它都會導致Firebase被反覆POST請求。</p>
P粉9787424052023-08-19 14:46:23
你的循環運行的原因是因為你沒有在副作用中設定onAuthStateChanged(),請嘗試以下操作
const FirebaseAuth = React.createContext({ user: null, loading: true, role: '', email: '', firstName: '', isActive: false, lastName: '', location: '', userID: '', }); export const FirebaseAuthProvider = ({ children }) => { const [user, setUser] = useState(null); const [role, setRole] = useState(null); const [email, setEmail] = useState(''); const [firstName, setFirstName] = useState(''); const [isActive, setIsActive] = useState(false); const [lastName, setLastName] = useState(''); const [location, setLocation] = useState(''); const [userID, setUserID] = useState(''); const [loading, setLoading] = useState(true); useEffect(() => { onAuthStateChanged(auth, (user) => { setLoading(true); if (user) { setUser(user); FirebaseFirestoreService.getUserData(user.uid).then((data) => { setUserID(user.uid); setUserRole(data.role); setEmail(data.email); setFirstName(data.firstName); setIsActive(data.isActive); setLastName(data.lastName); setLocation(data.location); }); setLoadingState(false); } else { setLoadingState(false); } }); // eslint-disable-next-line react-hooks/exhaustive-deps }, []); return ( <FirebaseAuth.Provider value={{ user, loading, role, email, firstName, lastName, isActive, location, userID, }} > {children} </FirebaseAuth.Provider> ); }; export default FirebaseAuth;