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

Reactjs 如何在应用程序的客户端内使用router.replace?,reactjs,redux,next.js,next-router,Reactjs,Redux,Next.js,Next Router,我试图使用Next.js router重定向未经授权的用户,使其无法访问包装在AdminLayout组件中的某些页面,但我遇到了此错误 错误:未找到路由器实例。您应该只使用“下一个/路由器” 在应用程序的客户端内部 有没有办法解决这个问题?render方法也会在服务器中执行,因此会出现异常 通常在渲染方法中加入副作用(例如重定向)是一种不良做法 您应该将它放在只在客户端运行的componentDidMount中 //其他导入 从“下一个/路由器”导入路由器; 类AdminLayout扩展了Re

我试图使用Next.js router重定向未经授权的用户,使其无法访问包装在
AdminLayout
组件中的某些页面,但我遇到了此错误

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


有没有办法解决这个问题?

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

通常在
渲染
方法中加入副作用(例如重定向)是一种不良做法

您应该将它放在只在客户端运行的
componentDidMount

//其他导入
从“下一个/路由器”导入路由器;
类AdminLayout扩展了React.Component{
componentDidMount(){
const{currentUser}=this.props;
如果(currentUser==未定义){
console.log(当前用户);
返回null;
}
if(currentUser==null){
console.log(当前用户);
//这就是我试图重定向的方式
替换('/admin/login');
}
}
render(){
const{currentUser}=this.props;
如果(currentUser==未定义){
console.log(当前用户);
返回null;
}
返回(
//其他无关代码
);
}
}
常量mapStateToProps=(状态)=>({
currentUser:state.user.currentUser,
});
导出默认连接(MapStateTops)(AdminLayout);
如果您想在服务器端重定向,则需要使用在服务器上运行的
getInitialProps
/
getServerProps
,这些方法在服务器端获取服务器的
请求
响应
,使您能够从服务器重定向

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

有没有办法在页面呈现之前进行重定向?更新了应答器,但getInitialProps()不适用于页面而不适用于组件?(AdminLayout是一个组件,getInitialProps不在此处运行)正确,您不能从组件内重定向到其他页面。通过componentDidMount的客户端重定向或页面级别的服务器端重定向。有什么建议吗?
class AdminLayout extends React.Component {
   static getInitialProps ({ res }) {
      if(someCondition) {
        res.redirect('/your-path');
      }
   }
   ...
}