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

How to use router.replace inside the client side of your app?

我正在尝试使用 Next.js 路由器来重定向未经授权的用户,使其无法访问包含在 AdminLayout 组件中的某些页面,但我遇到了这个错误。

Error: No router instance found. You should only use "next/router" inside the client side of your app.

// 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);

有什么办法可以解决这个问题?

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 & response 这使您能够从服务器重定向。

class AdminLayout extends React.Component {
   static getInitialProps ({ res }) {
      if(someCondition) {
        res.redirect('/your-path');
      }
   }
   ...
}