Next js警告:无法在呈现其他组件(`Home`)时更新组件(`Router`),定位`Home`中错误的setState()调用

7gs2gvoe  于 2023-06-22  发布在  其他
关注(0)|答案(1)|浏览(294)

我在我的Next.js项目中使用Firebase作为后端。在使用路由时,我得到一些错误:
密码:

"use client";
import { useAuthContext } from "@/context/AuthContext";
import Login from "./login/Loginpage";
import { useRouter } from "next/navigation";
import React from "react";

export default function Home() {
  const { user } = useAuthContext();
  const router = useRouter();

  const data = user == null ? <Login /> : router.push("../admin");
  return <>{data}</>;
}

一切正常,但我在控制台得到以下错误。

Warning: Cannot update a component (`Router`) while rendering a different component (`Home`). To locate the bad setState() call inside `Home`, follow the stack trace as described in https://reactjs.org/link/setstate-in-render
    at Home (webpack-internal:///(app-client)/./src/app/adminLogin/page.js:20:91)
    at InnerLayoutRouter (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/layout-router.js:227:11)
    at RedirectErrorBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:73:9)
    at RedirectBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/redirect-boundary.js:81:11)
    at NotFoundBoundary (webpack-internal:///(app-client)/./node_modules/next/dist/client/components/not-found-boundary.js:59:11)

我尝试了很多来修复它下面的代码没有给予任何错误,但DOM是加载路由之前

'use client'
import React from "react";
import { useAuthContext } from "@/context/AuthContext";
import { useRouter } from "next/navigation";
import Login from "./login/Loginpage";
function Page() {
    const { user } = useAuthContext()
    const router = useRouter()

    React.useEffect(() => {
        if (user == null) router.push("../admin")
    }, [user])

    return (<><Login/></>);
}

export default Page;

有没有办法在DOM加载之前进行路由,或者有没有办法解决第一个代码中的错误?

ggazkfy8

ggazkfy81#

可以添加条件呈现,以确保组件仅在条件为真时才呈现

return (
<>{user && <Login />}</>
)

相关问题