Lau*_*ris 5 routes token reactjs next.js
当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 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;
Run Code Online (Sandbox Code Playgroud)
看来您正在使用下一个路由器依赖项?
尝试使用next/router
(nextjs 的默认依赖项),它在我的代码中工作正常:
import Router from "next/router";
{ other code... }
Router.push("/auth/signup");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
33989 次 |
最近记录: |