英文:
useEffect hook for login via local storage
问题
//模块
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
//样式
import styles from "./page.module.sass";
//组件
import NewCV from "./components/newCv";
import Cvs from "./components/cvs";
import PersonalInfo from "./components/personalInfo";
import LayoutPicker from "./components/LayoutPicker";
//帮助器
import { vaildToken } from "@/app/authorization";
export default function MyPage() {
const router = useRouter();
const [catType, setCatType] = useState(0);
const cat = (type) => setCatType(type);
const [valid, setValid] = useState(false);
const [role, setRole] = useState('')
useEffect(() => {
const res = vaildToken(localStorage.getItem("token"));
setValid(res[0]);
setRole(res[1]);
if (valid !== true && role !== "USER") {
router.push("/login");
}
}, [valid, role]);
console.log(valid, role)
return (
<main className={styles.main}>
{valid !== true && role !== "USER" ? (
<div className={styles.container}>
<LayoutPicker cat={cat} />
{catType == 1 ? <Cvs /> : catType == 2 ? <NewCV /> : <PersonalInfo />}
</div>
) : (
<></>
)}
</main>
);
}
英文:
I'm creating a React + Next.js app with authorisation and I need to get token from local storage. If I do this without useEffect, there is an error of undefined localstorage, but with use effect my redirects don't work, maybe you know where am I wrong?
"use client";
//modules
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
//styles
import styles from "./page.module.sass";
//components
import NewCV from "./components/newCv";
import Cvs from "./components/cvs";
import PersonalInfo from "./components/personalInfo";
import LayoutPicker from "./components/LayoutPicker";
//helpers
import { vaildToken } from "@/app/authorization";
export default function MyPage() {
const router = useRouter();
const [catType, setCatType] = useState(0);
const cat = (type) => setCatType(type);
const [valid, setValid] = useState(false);
const [role, setRole] = useState('')
useEffect(() => {
const res = vaildToken(localStorage.getItem("token"));
setValid(res[0]);
setRole(res[1]);
if (valid !== true && role !== "USER") {
router.push("/login");
}
}, [valid, role]);
console.log(valid, role)
return (
<main className={styles.main}>
{valid !== true && role !== "USER" ? (
<div className={styles.container}>
<LayoutPicker cat={cat} />
{catType == 1 ? <Cvs /> : catType == 2 ? <NewCV /> : <PersonalInfo />}
</div>
) : (
<></>
)}
</main>
);
}
答案1
得分: 1
更改条件如下,因为您不会立即获得状态值。
if (res[0] !== true && res[1] !== "USER") {
router.push("/login");
}
希望它能工作。
英文:
Change the condition as follows cause you won't get the state value immediately.
if (res[0] !== true && res[1] !== "USER") {
router.push("/login");
}
Hope, it'll work.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论