简体   繁体   English

每次组件在 React ContextAPI 下呈现时获取登录用户

[英]Get logged user every time the component renders under React ContextAPI

I'm using ContextAPI in a small React project, I use HttpOnly Cookie to store the user's token when I hit the /login endpoint.我在一个小型 React 项目中使用 ContextAPI,当我点击/login端点时,我使用HttpOnly Cookie来存储用户的令牌。

This is UserContext.js shown bellow, which encapsulates all the components (children) in App.js这是下面显示的UserContext.js ,它封装了App.js中的所有组件(子组件)

import axios from "axios";
import { createContext, useEffect, useState } from "react";

const UserContext = createContext();

const UserContextProvider = ({ children }) => {
  const [loggedUser, setLoggedUser] = useState(undefined);

  const checkLoggedIn = async () => {
    const response = await axios.get(`${process.env.REACT_APP_URL}/logged-in`);
    setLoggedUser(response.data);
  };

  useEffect(() => {
    checkLoggedIn();
  }, []);

  return (
    <UserContext.Provider value={{ loggedUser }}>
      {children}
    </UserContext.Provider>
  );
};

export { UserContext };
export default UserContextProvider;

What I understand is when I log in, I setLoggedUser to the state from the /login response, and now it is available for all the children components of the context.我的理解是,当我登录时,我从/login响应setLoggedUser设置为 state,现在它可用于上下文的所有子组件。

Now I can navigate to all components wrapped by the context and print for example the email of the loggedUser , but what if the email changed while we're logged in?现在我可以导航到由上下文包装的所有组件并打印,例如 loggedUser 的loggedUser ,但是如果 email 在我们登录时发生了变化怎么办? I'll still see the old email on my components because the data is outdated in the state.我仍然会在我的组件上看到旧的 email,因为 state 中的数据已过时。 And what if token got invalidated on the server while we were logged in.. (The only case we'll get updated data is if I refresh the app because that will trigger useEffect in the context provider and refresh the state again)如果在我们登录时令牌在服务器上失效怎么办..(我们将获得更新数据的唯一情况是如果我刷新应用程序,因为这将触发上下文提供程序中的 useEffect 并再次刷新 state)

Should I also pass the checkLoggedIn function through the context's value property to make it available for other components and then use it in UseEffect in every component?我是否还应该通过上下文的value属性传递checkLoggedIn function 以使其可用于其他组件,然后在每个组件的 UseEffect 中使用它? Or is there a better solution for this problem?或者这个问题有更好的解决方案吗?

After the latest comment if you want to check for email on every re-render then you can remove [] from useEffect as stated above in the comments by @abu dujana.在最新评论之后,如果您想在每次重新渲染时检查 email,那么您可以按照@abu dujana 的评论中所述从 useEffect 中删除 []。

import axios from "axios";
import { createContext, useEffect, useState } from "react";

const UserContext = createContext();

const UserContextProvider = ({ children }) => {
  const [loggedUser, setLoggedUser] = useState(undefined);

  const checkLoggedIn = async () => {
    const response = await axios.get(`${process.env.REACT_APP_URL}/logged-in`);
    setLoggedUser(response.data);
  };

  useEffect(() => {
    checkLoggedIn();
  });

  return (
    <UserContext.Provider value={{ loggedUser }}>
      {children}
    </UserContext.Provider>
  );
};

export { UserContext };
export default UserContextProvider;

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

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