reactjs - Routes.push() 在 NextJS 中没有按预期工作
问题描述
当用户尝试在未经身份验证的情况下访问应用程序的仪表板时,我试图将用户重定向到主页,但 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
(来自 nextjs 的默认依赖项),它在我的代码中运行良好:
import Router from "next/router";
{ other code... }
Router.push("/auth/signup");
推荐阅读
- c# - MVC 5 - How to update relational table using EF code first
- vscode-remote - 从用户A切换到用户B
- python - 如何编写一个或条件来以 Python 方式检查子字符串?
- ant - 如何使用ant中的scp任务一次将不同目录中的多个文件从本地机器复制到远程机器?
- javascript - 在 SCSS 中动态堆叠图像
- javascript - 跨 react-table 实现全局搜索过滤器:React+ react-table
- python - 使用 Python 读取 Cassandra 时获取 dict 而不是 OrderedMapSerializedKey
- sparql - 从 dbpedia 查询中仅返回标签列和人口
- c# - 如何在 Entity Framework Core 中限制链接实体
- javascript - 在模板文字 JS 内循环