[我正在尝试使用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);
任何解决此问题的方法?
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