【问题标题】:NextJS useEffect locaStorage issueNext JS useEffect localStorage 问题
【发布时间】:2020-04-28 14:42:04
【问题描述】:

我正在尝试从 localstorage 获取字符串并在某些条件下检查它并根据 localstorage 中的值重定向页面

但问题是,我可以在页面重定向到原始页面之前看到该页面几秒钟

基本上是它的身份验证之类的东西

这里是代码

import React from "react";
import AdminDashboard from "../components/AdminDashboard";
import Router from "next/router";
import SignIn from "../pages/index";
import useRouter from "next/router";
import fetch from "isomorphic-unfetch";

var userType;
export default function Test({ token }) {
  const [userType, setuserType] = React.useState(false);

  React.useLayoutEffect(() => {
    if (userType !== true) {
      const lt = localStorage.getItem("userType");
      if (lt !== true) Router.push("/");
    }
    return () => {};
  }, []);
  {
    console.log(token);
  }
  return (
    <div>
      <AdminDashboard>Admin Page </AdminDashboard>
    </div>
  );
}

【问题讨论】:

  • 我认为你不能在本地存储中存储布尔值,请检查 lt 的值和类型

标签: reactjs next.js


【解决方案1】:

您只能在客户端中呈现页面以避免页面闪烁。

另一方面,您可以只使用 useEffect。

const Page = null;

React.useEffect(() => {
    if (userType !== true) {
      const lt = localStorage.getItem("userType");
      if (lt !== true) Router.push("/");
    } else {
      Page = (
        <div>
          <AdminDashboard>Admin Page </AdminDashboard>
        </div>
      )
    }
}, [])

return Page

【讨论】:

    猜你喜欢
    • 2021-11-13
    • 2022-01-18
    • 2020-10-30
    • 2021-08-07
    • 1970-01-01
    • 2023-03-20
    • 2021-08-16
    • 2023-03-18
    • 2020-07-21
    相关资源
    最近更新 更多