拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 在React中,等待在sessionStorage中查找值的正确方法是什么?

在React中,等待在sessionStorage中查找值的正确方法是什么?

白鹭 - 2022-03-02 1964 0 0

我正在使用 React 16。我有一个钩子,用于确定会话令牌是否已存盘在会话存盘中......

import { useEffect } from 'react';
import { useAuthenticationState, useAuthenticationDispatch } from '../context';

const useAuthentication = () => {
  const authenticationState = useAuthenticationState();
  const updateAuthenticationState = useAuthenticationDispatch();

  useEffect(() => {
    const auth_token = sessionStorage.getItem('token');
    console.log("auth token: "   auth_token);
    updateAuthenticationState({
      type: 'field',
      fieldName: 'isAuthenticated',
      payload: !!auth_token,
    });
  }, [updateAuthenticationState]);

  const isAuthenticated = authenticationState.isAuthenticated;

  return {
    isAuthenticated,
  };
};

export default useAuthentication;

我想将存盘在会话存盘中的值传递给一个组件,该组件将呈现另一个组件或根据我的钩子的值重定向...

const DirectoryApp = () => {
  console.log("starting get hook value ...");
  const { isAuthenticated } = useAuthentication();
  console.log("is auth:"   isAuthenticated);

  return (
      <Router>
        ...
                  <PrivateRoute
                  authed={isAuthenticated} path="/unapproved-list/"
                  component={UnapprovedList}
                  />

但是这条线

const { isAuthenticated } = useAuthentication();

没有正确获取 sessionStorage 中的值——它总是初始回传 false。我认为这是因为我没有等待钩子回传的结果,但是如果我这样做

const { isAuthenticated } = await useAuthentication();  

我收到错误

Syntax error: Unexpected reserved word 'await'. (24:31)

我如何正确等待钩子回传的值?

uj5u.com热心网友回复:

Effect 在DirectoryApp组件的初始渲染之后被呼叫这意味着您的useAuthentication钩子获取存盘在 中的任何内容authenticationState并在不依赖于 useEffect 钩子内部代码的情况下回传它,此时 ant 回传 DirectoryApp 组件,DirectoryApp 使用此初始值呈现,并且仅在此之后才会执行效果。

由于您提供的代码中没有异步代码,因此无需等待。

根据您的汇入和代码结构,我假设您正在尝试使用 React.Context 和内部的 reducer 来管理身份验证状态。在这种情况下,您有某种型别的 AuthenticationProvider 组件,DirectoryApp所以您可以通过将读取的会话存盘移动到 reducer 的第三个初始值设定项自变量来解决该问题:

const reducer = (state, action) => {
    // reducer logic
};

const StateContext = createContext();
const DispatchContext = createContext();
const useAuthenticationState = () => useContext(StateContext);
const useAuthenticationDispatch = () => useContext(DispatchContext);

const AuthenticationProvider = ({ children }) => {
    const [state, dispatch] = useReducer(reducer, { isAuthenticated: false }, (arg) => {
        const auth_token = sessionStorage.getItem('token');
        
        return { ...arg, isAuthenticated: !!auth_token };
    });
    
    return (
        <DispatchContext.Provider value={dispatch}>
            <StateContext.Provider value={state}>
                {children}
            </StateContext.Provider>
        </DispatchContext.Provider>
    );
};

const App = () => (
    <AuthenticationProvider>
      <DirectoryApp />
    </AuthenticationProvider>
);

sessionStorage.getItem是一个同步函式,因此您将在第一次渲染DirectoryApp.

标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *