当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 Route.push() 不起作用。
我试图将 Router.push('/') 更改为 Router.push('/hey') -> 一个不存在的页面,这奏效了,路由改变了。此外,当我尝试访问像 Router.push('/auth/signin') 这样的路径时,它在 Router.push('/auth') 工作时不起作用
import { isAuthenticated } from "../helpers/auth";
import { Component } from "react";
import { Router } from "../routes";
class Ads extends Component {
// static async getInitialProps(ctx) {
// if (ctx && ctx.req) {
// console.log(ctx);
// //ctx.res.writeHead(302, { Location: `/` });
// ctx.res.end();
// } else {
// console.log("client side");
// console.log(localStorage.getItem("auth-token"));
// }
// }
handleAuthentication = () => {
if (localStorage.getItem("auth-token")) {
return true;
}
};
componentDidMount() {
if (this.handleAuthentication()) {
console.log("hey");
} else {
Router.pushRoute("/auth/signup");
}
}
render() {
return (
<div>
<p> Dashboard </p>
</div>
);
}
}
export default Ads;
最佳答案
看来您正在使用 next-router依赖?
尝试使用 next/router
(来自 nextjs 的默认依赖项),它在我的代码中运行良好:
import Router from "next/router";
{ other code... }
Router.push("/auth/signup");
关于reactjs - Routes.push() 在 NextJS 上没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57454034/