【问题标题】:How to change url without refreshing to the next page using Next Js useRouter?如何使用 Next Js useRouter 在不刷新到下一页的情况下更改 url?
【发布时间】:2022-02-01 01:32:19
【问题描述】:

我正在使用 Next.js,我想知道如何在不刷新的情况下更改同一页面上的 url。我正在使用 shallow=true 但它仍然呈现到下一页。

这是我的代码:

<Tabs>
   <Tab href='test/1' label='Sample Exam'/>
   <Tab href='test/1/exam' label='Test Exam'/>
</Tabs>
<TabPanel value={tabvalue} index={0}>
   <SampleComponent />
</TabPanel> 
<TabPanel value={tabvalue} index={1}>
   <TestComponent />
</TabPanel> 

这是逻辑但不起作用

    const [tabValue, setTabValue] = React.useState(0);
    const router = useRouter();
    const handleChange = (event: React.ChangeEvent<{}>, newValue: number) => {
        setTabValue(newValue);
        useEffect(() => {
            router.replace('/test/1', '/test/1/exam', { shallow: true});
        }, []);
    };

我已经测试了 router.push 它不起作用并且 windows 替换状态是一个坏主意。选项卡将如下所示。

     Sample Exam          |        Test Exam

如果您单击样本考试,它将显示与考试相同的样本详细信息,但必须在同一页面上。

谢谢。

【问题讨论】:

    标签: reactjs next.js next-router


    【解决方案1】:

    旧帖子,但有人可能会觉得它有用:

    问题是,你不能浅层路由'/test/1''/test/1/exam',因为 nextjs 使用基于文件系统的路由。 在您的页面目录中,'test/1' 将指向test/1/index.js,或者如果您使用的是动态路径,则它是test/[id].js。 但是'/test/1/exam' 将指向test/1/exam/index.js,或者在动态路径的情况下,它可以是test/[id]/exam/index.js。 这两个文件不在不同的级别,因此浅层路由不起作用。

    您可以尝试添加查询,例如:test/1?show=exam,因为只能使用 1 个文件来处理:test/[id].js。浅路由会以这种方式工作。

    另一种方法是在样本检查的情况下也显示一些内容。例如而不是使用'test/1',它可能是'test/1/sample',而'test/1/exam' 将保留。在这种情况下,单个文件将能够使用浅路由处理两个单独的选项:test/[id]/[slug].js

    查看更多:https://nextjs.org/docs/routing/introductionhttps://nextjs.org/docs/routing/dynamic-routes

    【讨论】:

      猜你喜欢
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      • 2016-05-25
      • 2011-09-01
      • 1970-01-01
      • 2014-11-06
      相关资源
      最近更新 更多