我正在使用 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
.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/400385.html
下一篇:返回列表