javascript - 使用 Context API 给我未定义的信息

标签 javascript reactjs

所以我使用 Auth0 进行用户注册。我正在尝试获取 sub:value 下的用户 ID 添加到我的数据库中以识别用户的帖子。我正在尝试使用 Context API 来获取用户信息并将其放入我的数据库中。

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(尝试从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;

这给了我用户:未定义

在我的index.js中我有这个

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

我相信这给了我这些结果:

enter image description here

所以我想知道为什么我的 Context API 不起作用并给我 user: undefined

最佳答案

您将在组件首次安装时记录用户,这比等待 auth0FromHook.getUser() 调用完成之前要早得多。将其记录在 componentDidUpdate 中,或者检查父组件是否该值可用,并且在可用之前不要挂载子组件。

关于javascript - 使用 Context API 给我未定义的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60514671/

相关文章:

JavaScript 没有取消我的链接操作

javascript - AngularJS - 努力将值(value)传递给工厂

reactjs - React Router V6 与 { BrowserRouter, Routes, Route } 路由不起作用,抛出空白页面

javascript - setState 不适用于多个 onClick 函数

html - create-react-app 在服务器上部署时图标 png 文件加载失败

reactjs - 在 React.js 中的 setState 之后自动滚动到呈现的元素

reactjs - 为什么初始状态为null时createSlice会报错?

javascript - 如何让图片随机移动并转向页面周围变化的方向? (使用 jQuery 和 CSS)

javascript - 有没有办法在万无一失的沙箱中使用 jsdom?

javascript - 悬停在父元素上时,显示子元素(下拉导航)