如何使用可观察对象为提供程序组件(反应/ Firebase)更新上下文提供程序?

时间:2020-04-10 23:22:17

标签: javascript reactjs firebase observable

我遇到了在我的应用程序中实现firebase-auth上下文的问题。在我尝试使用Firebase处理持久性之前,一切似乎都很好。如下所示,firebase使用名为onAuthStateChanged的可观察对象来捕获已登录的用户,并且可以用来更新auth对象以通过提供程序传递。刷新该应用程序时,可观察对象最终将再次返回auth对象,该对象应更新提供程序,并更新react树中使用auth上下文的所有组件。

起初我得到一个错误:TypeError: Cannot read property 'user' of undefined

如果我在使用组件中记录状态,则会得到:Auth state within component undefined

这是我的组件,充当其余应用程序组件树的提供者。

AuthContext.js
import React from "react";
import * as firebase from "firebase/app";
import { firebaseAuth } from "../reducers/AuthReducer";

export const Auth = React.createContext();

export const AuthProvider = (props) => {
  const [state, dispatch] = React.useReducer(
    firebaseAuth,
    { user: {} },
    firebase.auth().onAuthStateChanged((user) => {
      return user;
    })
  );

  return (
    <Auth.Provider value={{ state, dispatch }}>{props.children}</Auth.Provider>
  );
};

这是我使用提供的身份验证上下文的组件:

RightPanel.js
import React from "react";
import HomePageAuth from "./homepageauth/HomePageAuth";
import "./rightpanel.module.less";
import NavCluster from "../../../nav/navcluster/NavCluster";
import { Auth } from "../../../../contexts/AuthContext";

const RightPanel = () => {
  const { state, dispatch } = React.useContext(Auth);

  console.log("Auth state within component", state);

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        marginTop: "80px",
        width: "50%",
      }}
    >
      {state.user ? <NavCluster /> : <HomePageAuth />}
    </div>
  );
};

export default RightPanel;

1 个答案:

答案 0 :(得分:0)

在初始化中,您将返回用户,而不是将用户作为键的对象。参见https://reactjs.org/docs/hooks-reference.html#lazy-initialization

firebase.auth().onAuthStateChanged((user) => {
  return {user};
})