【问题标题】:How to use observables to update a context provider for purposes of a Provider component (React/Firebase)?如何使用 observables 来更新上下文提供者以用于提供者组件(React/Firebase)?
【发布时间】:2020-04-10 23:22:17
【问题描述】:

我遇到了在我的应用中实现 firebase-auth 上下文的问题。在我尝试使用 firebase 处理持久性之前,一切似乎都很好。正如您在下面看到的,firebase 使用一个名为 onAuthStateChanged 的 observable 来获取登录用户,这可用于更新身份验证对象以通过提供程序传递下来。当您刷新该应用程序时,observable 最终将再次返回一个 auth 对象,该对象应更新提供程序,并更新反应树中使用 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;

【问题讨论】:

    标签: javascript reactjs firebase observable


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2022-08-08
      • 1970-01-01
      • 2018-11-03
      • 1970-01-01
      • 2020-08-07
      相关资源
      最近更新 更多