firebase 快照没有获取 currentUser

firebase snapshot not getting currentUser

我正在尝试在控制台中获取当前用户,但在 react-native 中未定义。它是 Firebase 8.3。 这是我的 firebase init

import firebase from "firebase";
// import { initializeApp } from "firebase/app";
const firebaseConfig = {
  //api
};
// Initialize Firebase
const app = firebase.initializeApp(firebaseConfig);
export default firebase;

这是操作代码,与互联网上的文档相同

 firebase
      .firestore()
      .collection("user")
      .doc(firebase.auth().currentUser.uid)
      .get()
      .then((snapshot) => {
        if (snapshot.exists) {
          console.log(snapshot.data());
          dispatch({ type: USER_STATE_CHANGE, currentUser: snapshot.data() });
        } else {
          console.log("does not exist, console from action ");
        }

这里是我的redux store代码,据我所知比较可疑

const store = createStore(Reducers, applyMiddleware(thunk))
 return (
      <Provider style={styles.center} store={store}>
       <Main/>
      </Provider>
    );

和main.js

function Main(props) {
  useEffect(() => {
    props.fetchUser();
  }, []);
  if (props.currentUser == undefined) {
    return (
      <View>
        <Text>No Data</Text>
      </View>
    );
  } else {
    return (
      <View>
        <Text>{props.currentUser.name} is logged in now !</Text>
      </View>
    );
  }
}
const mapStateToProps = (state) => {
  return {
    currentUser: state.user.currentUser,
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    fetchUser: () => dispatch(fetchUser()),
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(Main);

我的猜测(很难从您共享的代码片段中确定)是从 Firestore 加载用户数据的代码在 page/app 加载时运行,而 Firebase 尚未完成运行时恢复当前用户。

当 page/app 加载时,Firebase 会自动从本地存储中恢复用户凭据。这需要它调用服务器(其中包括查看帐户是否已被禁用),这可能需要一些时间。在进行此调用时,您的主要代码仍在继续,此时 firebase.auth().currentUser 的值为 null

因此,如果您不将加载用户配置文件的代码同步到 Firebase 的恢复操作,您最终将过早加载数据,此时用户尚未 re-signed .

解决方案是监听身份验证状态的变化,并做出响应,而不是假设 firebase.auth().currentUser 总是正确的。有关如何执行此操作的示例,请参阅 getting the current user:

上的 Firebase 文档中的第一个代码片段
firebase.auth().onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    var uid = user.uid;
    //  This is where you can load the user profile from Firestore
    // ...
  } else {
    // User is signed out
    // ...
  }
});