如何在类组件中访问 NextJS Router

时间:2021-07-03 14:35:08

标签: reactjs next.js

我在 NextJS 中有以下 HOC。

我希望通过 withRouter HOC 为类组件访问 NextJS 路由器,如下所示。

import UserManager from "../managers/user_manager";
import LogInPage from "../pages/auth/login";
import React from "react";
import { withRouter } from 'next/router'

export default function EnsureAuthenticated(OriginalComponent) {
    class AuthHOC extends React.Component {
        constructor(props) {
            super(props);
        }
        componentDidMount() {
            this.loggedInUser = UserManager.getLoggedInUser();
        }
        render() {
            if (!this.loggedInUser) {
                this.props.router.push(LogInPage.routePath);
            }
            return <OriginalComponent />
        }
    }
    return withRouter(AuthHOC);
}

但这是我不断收到的错误:

Server Error
Error: No router instance found. you should only use "next/router" inside the client side of your app. https://nextjs.org/docs/messages/no-router-instance

我要采取哪些不同的方式来解决这个问题? 谢谢。

1 个答案:

答案 0 :(得分:1)

NextJS 使用 SSR,因此在预渲染(SSR 或 SSG)期间,您尝试访问不受支持的路由器方法推送 (this.props.router.push(LogInPage.routePath))。

您应该在 componentDidMount 方法中使用以下代码

if (!this.loggedInUser) {
      this.props.router.push(LogInPage.routePath);
}

如下图

  componentDidMount() {
            this.loggedInUser = UserManager.getLoggedInUser();

            if (!this.loggedInUser) {
                    this.props.router.push(LogInPage.routePath);
            }
        }