简体   繁体   English

使用上下文 API 给我未定义

[英]Using the Context API gives me undefined

So I'm using Auth0 for my user sign up.所以我使用 Auth0 进行用户注册。 I'm trying to get the user id under sub:value to add to my database to identify with the post of a user.我正在尝试获取sub:value下的用户 ID,以添加到我的数据库中以识别用户的帖子。 I'm trying to use a Context API in order to get the user info to put in my database.我正在尝试使用上下文 API 来获取用户信息以放入我的数据库中。

react-auth0-spa.js react-auth0-spa.js

// src/react-auth0-spa.js
import React, { useState, useEffect, useContext } from "react";
import createAuth0Client from "@auth0/auth0-spa-js";


const DEFAULT_REDIRECT_CALLBACK = () =>
  window.history.replaceState({}, document.title, window.location.pathname);

export const Auth0Context = React.createContext();
export const useAuth0 = () => useContext(Auth0Context);
export const Auth0Provider = ({
  children,
  onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
  ...initOptions
}) => {
  const [isAuthenticated, setIsAuthenticated] = useState();
  const [user, setUser] = useState();
  const [auth0Client, setAuth0] = useState();
  const [loading, setLoading] = useState(true);
  const [popupOpen, setPopupOpen] = useState(false);

  useEffect(() => {
    const initAuth0 = async () => {
      const auth0FromHook = await createAuth0Client(initOptions);
      setAuth0(auth0FromHook);

      if (window.location.search.includes("code=") &&
          window.location.search.includes("state=")) {
        const { appState } = await auth0FromHook.handleRedirectCallback();
        onRedirectCallback(appState);
      }

      const isAuthenticated = await auth0FromHook.isAuthenticated();

      setIsAuthenticated(isAuthenticated);

      if (isAuthenticated) {
        const user = await auth0FromHook.getUser();
        setUser(user);
      }

      setLoading(false);
    };
    initAuth0();
    // eslint-disable-next-line
  }, []);

  const loginWithPopup = async (params = {}) => {
    setPopupOpen(true);
    try {
      await auth0Client.loginWithPopup(params);
    } catch (error) {
      console.error(error);
    } finally {
      setPopupOpen(false);
    }
    const user = await auth0Client.getUser();
    setUser(user);
    setIsAuthenticated(true);
  };

  const handleRedirectCallback = async () => {
    setLoading(true);
    await auth0Client.handleRedirectCallback();
    const user = await auth0Client.getUser();
    setLoading(false);
    setIsAuthenticated(true);
    setUser(user);
  };
  return (
    <Auth0Context.Provider
      value={{
        isAuthenticated,
        user,
        loading,
        popupOpen,
        loginWithPopup,
        handleRedirectCallback,
        getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
        loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
        getTokenSilently: (...p) => auth0Client.getTokenSilently(...p),
        getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
        logout: (...p) => auth0Client.logout(...p)
      }}
    >
      {children}
    </Auth0Context.Provider>
  );

};

other.js (trying to get user info from react-auth0-spa.js) other.js (尝试从 react-auth0-spa.js 获取用户信息)

class AddAlbum extends Component {
  constructor(props) {
    super(props);
 }

componentDidMount() {
    let value = this.context;
    console.log(value);

  }

render() {
    return (
)
}
AddAlbum.contextType = Auth0Context;

This gives me user: undefined这给了我user: undefined

In my index.js I have this在我的 index.js 我有这个

ReactDOM.render(
  <Auth0Provider
    domain={config.domain}
    client_id={config.clientId}
    redirect_uri={window.location.origin}
    onRedirectCallback={onRedirectCallback}
  >
    <App />
  </Auth0Provider>,
  document.getElementById("root")
);

Which I believe is giving me these results:我相信这给了我这些结果:

在此处输入图片说明

So I'm wondering why my Context API isn't working and giving me user: undefined .所以我想知道为什么我的 Context API 不起作用并给我user: undefined

You're logging the user when the component first mounts, which is long before the await auth0FromHook.getUser() call will complete.您在组件第一次挂载时记录用户,这是在 await auth0FromHook.getUser() 调用完成之前很久。 Log it in a componentDidUpdate , or check in a parent if that value is available, and don't mount the child component until it is.将它记录在componentDidUpdate ,或者如果该值可用,则检查父componentDidUpdate ,并且在它可用之前不要挂载子组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM