标签: next-router

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

我正在尝试使用 Next.js 路由器重定向未经授权的用户访问封装在AdminLayout组件中的某些页面,但出现此错误。

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

未找到路由器实例

// 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);
Run Code Online (Sandbox Code Playgroud)

有任何解决这个问题的方法吗?

reactjs redux next.js next-router

5
推荐指数
1
解决办法
4661
查看次数

如何访问 Next.JS 自定义 404 页面上的当前路由?

我的 Next.JS 应用程序 (404.js) 中有一个自定义 404 页面。在页面上,我想显示类似 的消息The route <strong>/not-a-route</strong> does not exist,但是当使用 Next.js 的useRouter()和时router.pathname,路由器认为我已打开/404并显示The route <strong>/404</strong> does not exist。如何在自定义 404 页面中访问我所在的实际路线?

export const NotFound: React.FC = () => {
  const router = useRouter();
  console.log(router.pathname) // prints /404
  return (
    <Layout title='Oops! Something went wrong!'>
      <div className={styles.container}>
        <h1>Oops! Something went wrong!</h1>
          <p>
            The route <strong>{router.pathname}</strong> does not exist.
          </p>
      </div>
    </Layout>
  );
};
Run Code Online (Sandbox Code Playgroud)

javascript reactjs next.js next-router

5
推荐指数
1
解决办法
4729
查看次数

在一个项目的“next.config.js”文件中指定的重定向路径已在所有项目中实施

有点奇怪...

我已经为我的项目之一的根索引页面指定了重定向路径。它没有问题,并将我重定向到正确的路径,但现在它将我重定向到我所有其他项目的根索引页面的相同路径。(尝试访问localhost:3000现在将我的所有项目重定向到localhost:3000/ggp )

我尝试重新启动服务器,删除原始项目中的 next.config.js 文件,注释掉重定向键,在原始项目和其他项目中使用不同的路径覆盖它,但都无济于事。

这是我第一次创建 next.config.js 文件,显然也是第一次使用重定向键。我遵循文档中的指导(https://nextjs.org/docs/api-reference/next.config.js/redirects)。

起初我认为这可能是因为我将 permanent 设置为 true,但这似乎是一个有点奇怪的功能,使其成为全局的,当我在开发模式(下一个开发)和调试下运行不同的项目时,一切正常工作它应该。所以我不确定该值是否在第一次使用时被缓存或其他什么。

有人以前遇到过这个问题/知道解决方法吗?我将不胜感激你的帮助!

原来的next.js。

module.exports = {
  async redirects() {
    return [
      {
        source: '/',
        destination: '/ggp',
        permanent: true,
      },
    ]
  },
}
Run Code Online (Sandbox Code Playgroud)

javascript node.js next.js next-router

5
推荐指数
1
解决办法
902
查看次数

如何根据当前动态页面使 Next.js 链接动态化?

我正在使用 Next.js 构建 LMS。到目前为止我的项目结构是localhost/courses/1。每门课程有 7 页。仪表板、作业、测试和测验、成绩册、资源、公告和花名册。我已准备好所有组件和页面。因此,如果我手动转到localhost/courses/1/assignmentslocalhost/courses/1323/roster等,则效果很好。

我想要做的是:当我单击作业链接时,我需要转到该特定课程的作业页面 - 类似localhost/courses/1/assignments. 目前,我已将 URL 硬编码为,/courses/1/[page]因此如果我单击指派,它将转到localhost/courses/1/assignment,或者如果我单击名册,它将转到localhost/courses/1/roster

如何使该路线动态化,以便当用户单击课程内的某个选项卡时,会将他们带到该特定课程的该页面?

我抬起头next/linknext/router但我仍然做不到。有什么帮助吗?

编辑:这是我的文件夹结构:

在此输入图像描述

就像我上面说的,现在我已经使用链接将某人发送给/courses/1/assignment例如。

如果您想查看该网站,它托管在我的应用程序中。

import Image from 'next/image';
import tools from "./sidebarData";
import SideBarItem from "./SidebarItem";

function Sidebar() {
    return (
        <div className="flex mt-8 ml-20">
            <div className="">
                <ul>
                    {Object.entries(tools).map(([key, {title, url, icon}]) => (
                        <SideBarItem key={key} title={title} Icon={icon} url={url}/>
                    ))}
                </ul>

            </div>
        </div>
    )
} …
Run Code Online (Sandbox Code Playgroud)

reactjs next.js dynamic-routing next-router

5
推荐指数
1
解决办法
9039
查看次数

Next.js:实现私有路由时,如何防止在重定向之前出现未经授权的路由/页面?

profile本质上,我为 Next.js 应用程序中的两个页面(即和)创建了一个 HOC,dashboard两个页面阻止用户在未经授权的情况下访问它们。

例子:pages/profile.js

import withAuth from "../components/AuthCheck/index";

function Profile() {
  return (
    <>
      <h1>Profile</h1>
    </>
  )
}


export default withAuth(Profile);
Run Code Online (Sandbox Code Playgroud)

我的身份验证组件/HOC:

import { useRouter } from 'next/router'
import { useUser } from '../../lib/hooks'
import { PageLoader } from '../Loader/index'

const withAuth = Component => {
  const Auth = (props) => {
    const { isError } = useUser(); //My hook which is calling /api/user see if there is a user
    const router = useRouter()


    if …
Run Code Online (Sandbox Code Playgroud)

reactjs higher-order-components next.js next-router

5
推荐指数
1
解决办法
1万
查看次数

router.query 在 next/router 中的 router.push 后未更新

我有一个问题,我需要在更新后获取查询参数。

在此示例中,当我将console.log重置router.query为空对象时(并且路线已更新)。

为什么?我缺少什么?

当我让它发挥router.push(/foo?page=1)作用时!

这是一个错误吗?

代码沙盒链接

import { useEffect } from "react";
import { useRouter } from "next/router";

export default function IndexPage() {
  const router = useRouter();

  useEffect(() => {
    console.log("router.query change", router.query);
  }, [router.query]);

  const changeRoute = () => {
    router.push("/foo", { query: { page: "1" } });
  };

  return (
    <div>
      <button onClick={changeRoute}> change route</button>
    </div>
  );
}
Run Code Online (Sandbox Code Playgroud)

reactjs next.js next-router

5
推荐指数
1
解决办法
6251
查看次数

如何将布局应用于 /pages 子文件夹中的所有路由?

我在/pages (next.js)文件夹和子文件夹中创建了一些路由/account。我想将布局应用于/account子文件夹中的所有页面。

如何在不将布局应用到 中的每个页面的情况下轻松做到这一点/account

例子

我想将布局应用于profile.jssettings.js

components/
pages/
 - home.js
 - account/
    - profile.js
    - settings.js
...
Run Code Online (Sandbox Code Playgroud)

任何有关架构的建议将不胜感激!

layout next.js next-router

5
推荐指数
1
解决办法
4242
查看次数

Next JS - 是否可以在不更改 URL 的情况下滚动到页面上的 ID?

我想通过单击滚动到页面的不同部分,但我不希望地址栏中的 URL 更新。

例如,about我的页面上有一个部分,其 ID 为:

<div id='about'>
Run Code Online (Sandbox Code Playgroud)

通过单击页面上的链接,我想滚动到此部分。我已经能够使用该<Link>组件和使用 来执行此router操作,但是使用这两个组件,我无法在不更新 URL 的情况下执行此操作。

例如,使用router,我会:

router.replace(`/#about`);
Run Code Online (Sandbox Code Playgroud)

这工作正常,除了 URL 更新为myurl.com/#about,因为我想将 URL 保留为myurl.com

我尝试使用第二个as参数来设置 URL,例如:

router.replace(`/#about`, '/');
Run Code Online (Sandbox Code Playgroud)

然而,这只是破坏了链接。

有人知道如何在不更新 URL 的情况下实现这一目标吗?我没有找到任何示例,文档中也没有任何有用的内容。

感谢任何能提供帮助的人!

next.js next-router

5
推荐指数
1
解决办法
6692
查看次数

当 next.js 路由器使用不同的查询推送相同的路由时,如何强制重新加载页面?

我正在开发一个带有/proudct?id=xxx路线的产品详细信息页面,当用户/proudct?id=1跳转到时/proudct?id=2,仅状态依赖性router.query.id发生变化,我想强制重新加载整个页面而不是更新某些状态。

next.js next-router

5
推荐指数
1
解决办法
1万
查看次数

如何与下一个路由器传递数据而不将其显示在 URL 中?

我正在使用下一个路由器,我想将数据传递到另一个页面,但我不希望数据显示在 URL 中

我有一个按钮,一旦单击它就会重定向到另一个页面并向myObject其传递一个对象。

const router = useRouter();
const myObject = {
  proprety1: "example1",
  proprety2: "example2",
  proprety3: "example3",
}
//...
<button
   onClick={() => {
     router.push({
       pathname: "/next-page",
       query: { data: JSON.stringify(myObject) },
     });
   }}
 >
   Navigate
</button>
Run Code Online (Sandbox Code Playgroud)

然后next-page我得到这个 URL :

http://localhost:3000/next-page?data=%7B"proprety1"%3A"example1"%2C"proprety2"%3A"example2"%2C"proprety3"%3A"example3"%7D

这工作起来很清楚,但它真的很难看,不仅如此,我不希望在 url 中向用户显示数据。

reactjs next.js next-router

5
推荐指数
1
解决办法
5931
查看次数