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

5 reactjs redux next.js next-router

我正在尝试使用 Next.js 路由器重定向未经授权的用户访问封装在AdminLayout组件中的某些页面,但出现此错误。

错误:未找到路由器实例。您应该只在应用程序的客户端内使用“next/router”。

未找到路由器实例

// 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);
Run Code Online (Sandbox Code Playgroud)

有任何解决这个问题的方法吗?

fel*_*osh 9

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);
Run Code Online (Sandbox Code Playgroud)

如果您想在服务器端重定向,您将需要使用在服务器上运行的getInitialProps/ ,这些方法在服务器端获取服务器& ,这使您能够从服务器重定向。getServerPropsrequestresponse

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