【问题标题】:How to access NextJS Router in class component如何在类组件中访问 NextJS Router
【发布时间】:2021-07-03 14:35:08
【问题描述】:

我在 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

我有什么不同的方法来解决这个问题? 谢谢。

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    NextJS 使用 SSR,因此在预渲染(SSR 或 SSG)期间,您尝试访问不受支持的路由器方法 push (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);
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-12-10
      • 2022-08-20
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2017-10-31
      • 2021-04-14
      • 2016-12-09
      相关资源
      最近更新 更多