【问题标题】:How to use router.replace inside the client side of your app?如何在应用程序的客户端内使用 router.replace?
【发布时间】:2020-09-18 06:42:37
【问题描述】:

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

错误:未找到路由器实例。你应该只使用“下一个/路由器” 在应用的客户端内。

// 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】:

    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,服务器端的这些方法会获取服务器@987654327 @ & response 使您能够从服务器重定向。

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

    【讨论】:

    • 有什么方法可以在页面呈现之前进行重定向?
    • 更新了答案
    • 但是 getInitialProps() 不是只适用于页面而不适用于组件吗? (AdminLayout是一个组件,这里不运行getInitialProps)
    • 正确,您不能从组件内重定向到其他页面。通过 componentDidMount 的客户端重定向或页面级别的服务器端。
    • 有什么建议吗?
    猜你喜欢
    • 2019-05-11
    • 2016-06-12
    • 2018-01-08
    • 2012-08-28
    • 2012-11-21
    • 2019-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-09-28
    相关资源
    最近更新 更多