React Redux Firebase登录后需刷新才加载props问题求助
Hey Alex, let’s tackle this frustrating issue you’re facing. It’s super annoying when you log in, navigate to your Dashboard, and have to refresh to get Firestore data—especially since your Firebase auth state is loading just fine. Let’s break down the most likely culprits and how to fix them:
1. Firestore Listeners Aren’t Reacting to Auth State Changes
The most common reason for this is that your Firestore data subscriptions aren’t re-triggering when the user logs in. If you set up listeners only on component mount (before the auth state is fully updated), they’ll run before the user’s uid exists, so no data gets fetched.
Fix for Functional Components (with Hooks)
Use the functional form of useFirestoreConnect to tie your queries to the auth state. This will re-run the query automatically when auth.uid becomes available:
import { useFirestoreConnect, isLoaded, isEmpty } from 'react-redux-firebase'; import { useSelector } from 'react-redux'; const Dashboard = () => { const { auth, profile } = useSelector(state => state.firebase); // Subscribe to Firestore data ONLY when user is logged in useFirestoreConnect(() => { if (auth.uid) { return [ { collection: 'users', doc: auth.uid } // Adjust to your target collection/doc ]; } return []; // Return empty if no user is logged in }); // Grab the fetched data from Redux store const userData = useSelector(state => state.firestore.data.users?.[auth.uid]); // Handle loading/empty states if (!isLoaded(userData)) return <div>Loading your data...</div>; if (isEmpty(userData)) return <div>No user data found.</div>; return ( <div className="dashboard"> <h1>Welcome back, {profile.displayName}!</h1> <p>Your registered email: {userData.email}</p> </div> ); }; export default Dashboard;
Fix for Class Components (with Connect HOC)
If you’re using class components, pass props to firestoreConnect so it reacts to auth state changes:
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { firestoreConnect } from 'react-redux-firebase'; class Dashboard extends Component { render() { const { auth, userData } = this.props; if (!auth.uid) return <div>Please log in to access your dashboard.</div>; if (!userData) return <div>Loading...</div>; return ( <div> <h1>Welcome {auth.displayName}</h1> <p>Account created on: {userData.createdAt.toDate().toLocaleDateString()}</p> </div> ); } } const mapStateToProps = (state) => ({ auth: state.firebase.auth, userData: state.firestore.data.users?.[state.firebase.auth.uid] }); // Tie Firestore queries to auth props export default connect(mapStateToProps)( firestoreConnect((props) => { return props.auth.uid ? [{ collection: 'users', doc: props.auth.uid }] : []; })(Dashboard) );
2. Check Your Redux Store Configuration
Make sure your store is set up to properly sync Firestore data with Redux. Double-check these key points:
- You’ve added
firestoreReducerto your root reducer - You’re using the
reduxFirestoreenhancer - If you’re storing user profiles in Firestore, enable
useFirestoreForProfilein your RRF config
Example store config:
import { createStore, combineReducers, compose } from 'redux'; import { firebaseReducer, reactReduxFirebase } from 'react-redux-firebase'; import { firestoreReducer, reduxFirestore } from 'redux-firestore'; import firebase from 'firebase/app'; import 'firebase/auth'; import 'firebase/firestore'; // Initialize Firebase const firebaseConfig = { /* Your Firebase config */ }; firebase.initializeApp(firebaseConfig); // React Redux Firebase config const rrfConfig = { userProfile: 'users', useFirestoreForProfile: true // Critical if you sync user profiles to Firestore }; // Combine reducers const rootReducer = combineReducers({ firebase: firebaseReducer, firestore: firestoreReducer }); // Create store with enhancers const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; const store = createStore( rootReducer, composeEnhancers( reactReduxFirebase(firebase, rrfConfig), reduxFirestore(firebase) ) ); export default store;
3. Clear Firestore Cache (If Needed)
Occasionally, local Firestore cache can cause stale data after login. You can force a fresh fetch from the server or clear persistence after login:
- Force server-side data fetch:
useFirestoreConnect(() => { if (auth.uid) { return [ { collection: 'users', doc: auth.uid, settings: { source: 'server' } // Bypass cache } ]; } return []; }); - Clear persistence on login (run this after successful auth):
firebase.firestore().clearPersistence() .then(() => console.log('Cache cleared')) .catch(err => console.error('Error clearing cache:', err));
Start with the first fix—toggling Firestore queries based on auth state—it’s the most likely solution here. If that doesn’t work, double-check your store config or try clearing the cache.
内容的提问来源于stack exchange,提问作者Alex Hyslop

