简体   繁体   English

为什么在 AuthContext.Provider 中登录后不设置数据

[英]Why in AuthContext.Provider does't set data after login

If I set in context provider sample data, I see this data in all nested components.如果我在上下文提供程序示例数据中设置,我会在所有嵌套组件中看到此数据。 But I need login to the account and in response, I get data about user for set in the global context and use in all components.但是我需要登录该帐户,作为响应,我会获取有关用户的数据,以便在全局上下文中设置并在所有组件中使用。

context/AuthProvider.tsx

const AuthContext = createContext<any>({});

export const AuthProvider = ({ children }: any) => {
  const [auth, setAuth] = useState({});

  return (
    <>
      <AuthContext.Provider value={{ auth, setAuth }}>{children}</AuthContext.Provider>
    </>
  );
};

hooks/useAuth.ts

const useAuth = () => {
  return useContext(AuthContext);
};

export default useAuth;

index.tsx

import { AuthProvider } from './context/AuthProvider';

const root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement);

root.render(
  <React.StrictMode>
    <AuthProvider>
      <App />
    </AuthProvider>
  </React.StrictMode>
);

I have App with BrowserRouter logic for not logged users redirect to login.我有带有 BrowserRouter 逻辑的应用程序,用于未登录的用户重定向到登录。 If logged, so go to the Homepage.如果已登录,则将 go 转到主页。 components/App/App.tsx

const AppContainer: FC<any> = () => {
  const { token } = useToken();

  return (
    <>
      <div className={'wrapper'}>
        <BrowserRouter>
          {!token ? <LoggedOutRoutes /> : <LoggedInRoutes />}
        </BrowserRouter>
      </div>
    </>
  );
};

const LoggedOutRoutes: FC<any> = () => (
  <Switch>
    <Route path="/" exact={true}>
      <Login />
    </Route>
    <Redirect from={'*'} to={'/'} />
  </Switch>
);

const LoggedInRoutes: FC = () => (
  <Switch>
    <Route path="/" exact={true} component={Homepage} />
  </Switch>
);

In login component sending request with data and I getting access_token and user data.在登录组件中发送带有数据的请求,我得到 access_token 和用户数据。 Now I need set user data in useAuth hook.现在我需要在 useAuth 挂钩中设置用户数据。

const Login: FC<any> = () => {
  const { setToken } = useToken();
  const { setAuth } = useAuth()

  const handleSubmit = async (event: any) => {
    event.preventDefault();

    const res = await API.login({
      login,
      password
    });

    const { access_token, user } = res;

    setToken(access_token);
    setAuth(user);

    window.location.reload();
  };

  return (
    <form onClick={handleSubmit}>
      // ...There i have submit form, not interesting
    </form>
  );
};

After reloading the page, my page will be Homepage where I won't use my context data from the provider but I have an empty object, why?重新加载页面后,我的页面将是主页,我不会使用来自提供商的上下文数据,但我有一个空的 object,为什么?

The problem is window.location.reload .问题是window.location.reload Any SPA will not retain data after a page refresh by default.默认情况下,任何 SPA 在页面刷新后都不会保留数据。

Now if you still want to persist that information even after page reload, i recommend to persist that info in localStorage.现在,如果您即使在页面重新加载后仍想保留该信息,我建议将该信息保留在 localStorage 中。 So something like this should work.所以这样的事情应该有效。

export const AuthProvider = ({ children }: any) => {
  const [auth, setAuth] = useState(localStorage.get('some-key') || {});

  const updateAuth = (auth) => {
    localStorage.set('some-key', auth);
    setAuth(auth);
  }

  return (
    <>
      <AuthContext.Provider value={{ auth, updateAuth }}>{children}</AuthContext.Provider>
    </>
  );
};

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

相关问题 为什么我无法解构“(0,_contexts_AuthContext__WEBPACK_IMPORTED_MODULE_1__.useAuth)(...)”的属性“登录”,因为它是未定义的 - Why am I getting Cannot destructure property 'login' of '(0 , _contexts_AuthContext__WEBPACK_IMPORTED_MODULE_1__.useAuth)(...)' as it is undefined authContext.login() 导致“拒绝在框架中显示‘login.microsoftonline.com…’,因为它将‘X-Frame-Options’设置为‘deny’” - authContext.login() causes “ Refused to display ‘login.microsoftonline.com…’ in a frame because it set ‘X-Frame-Options’ to ‘deny’ ” 使用私有路由后 AuthContext 组件出现问题 - Trouble with the AuthContext component after using a private route with it 登录流星后不加载数据 - The data don't load after login meteor 登录后Firebase无法获取数据 - Firebase can't get data after login 为什么data-url设置后返回未定义? - Why does data-url come back undefined after being set? 为什么我的ajax登录脚本不起作用? - Why does my ajax login script won't work? 登录后无法获取和检索用户数据 - can't get and retrive user data after login 为什么数据无法在视图中显示? - why does the data couldn't show in the viewpage? 登录后设置不记名令牌 - Set bearer token after login
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM