Redux在创建store 、传递给Reaction-Redux Provider
组件以及应用程序被挂载和呈现时就准备好了.真的没有什么需要判断的.
问题是您使用的初始isLogged
状态与未经身份验证的用户匹配.通常情况下,被验证不是简单的二进制函数,而实际上是一个三元函数,例如已验证、未验证和未知.如果您无法将状态初始化为"已确认"状态,则应从未知状态开始.
const initialState = {
isLogged: null, // <-- initially unknown
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: { ... }
});
...
const RouteGuard = () => {
const isLogged = useSelector(selectAuthState);
const router = useRouter();
useEffect(() => {
// Redirect to login page only if confirmed unauthenticated
if (isLogged === false) {
router.replace('/login');
}
}, [isLogged]);
...
// Authenticated not confirmed yet
if (isLogged === null) {
return null; // or loading indicator/spinner/etc
}
// Confirmed authentication
return isLogged
? /* logged in UI */
: null;
};
您提到过您在本地存储中有一些身份验证状态.您也许能够从本地存储中初始化状态.如果没有存储任何内容,则返回null
,因此您仍然需要上面的组件逻辑来处理UI.
示例:
const initialState = {
isLogged: JSON.parse(localStorage.getItem("authState")), // whatever was persisted, or null
};
const authSlice = createSlice({
name: "auth",
initialState,
reducers: { ... }
});
...