如何在应用程序客户端内部使用router.replace?

问题描述 投票:0回答:1

[我正在尝试使用Next.js路由器重定向未授权用户,以使其无法访问包装在AdminLayout组件内的某些页面,但出现此错误。

错误:找不到路由器实例。您只能使用“下一个/路由器”在您应用的客户端内部。

No router instance found

// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  render() {
    const { currentUser } = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace("/admin/login");
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);

任何解决此问题的方法?

reactjs redux next.js next-router
1个回答
0
投票

render方法也在服务器中执行,因此会出现异常。

通常,将副作用(例如重定向)放入render方法中是一种不良做法。>>

您应该将其放在仅在客户端运行的componentDidMount中。

// Other imports
import Router from "next/router";

class AdminLayout extends React.Component {
  componentDidMount() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }

    if (currentUser == null) {
      console.log(currentUser);
      //this is how I tried to redirect
      Router.replace('/admin/login');
    }
  }
  render() {
    const {currentUser} = this.props;

    if (currentUser === undefined) {
      console.log(currentUser);
      return null;
    }
    return (
      // Other irrelevant code
    );
  }
}

const mapStateToProps = (state) => ({
  currentUser: state.user.currentUser,
});

export default connect(mapStateToProps)(AdminLayout);

如果要在服务器端进行重定向,则需要使用在服务器

上运行的getInitialProps / getServerProps,在服务器端的这些方法将获得服务器request和[C0 ],使您可以从服务器重定向。
response
© www.soinside.com 2019 - 2024. All rights reserved.