首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Next.js上设置主页

在Next.js上设置主页
EN

Stack Overflow用户
提问于 2020-07-25 00:05:22
回答 5查看 15.5K关注 0票数 5

是否有人知道如何将Next.js中的任何特定页面定义为根(主页)

我一直在网上寻找,没有找到任何具体的解决办法。这应该是一个非常常见的用例。

还有另一个帖子,Using Next.js next-routes, how to define a home route for the base web page?,但是它建议为它创建一个服务器。

有什么“NextJ”设置主页的方法吗?

有什么想法吗?

提前感谢!

EN

Stack Overflow用户

发布于 2020-08-06 07:04:05

我在另一条帖子中发布了解决我问题的答案:

Next.js Redirect from / to another page

这个例子取自https://dev.to/justincy/client-side-and-server-side-redirection-in-next-js-3ile

我需要立即将访问我的根页面(mywebsite.com/)的用户转发到一个子页面,在本例中是: mywebsite.com/home。

在我的主index.js文件中粘贴以下任何一个,都会达到预期的结果:

有复制粘贴级别的示例。

客户端

代码语言:javascript
运行
复制
import { useRouter } from 'next/router'

function RedirectPage() {
  const router = useRouter()
  // Make sure we're in the browser
  if (typeof window !== 'undefined') {
    router.push('/home')
  }
}

export default RedirectPage

服务器端

代码语言:javascript
运行
复制
import { useRouter } from 'next/router'

function RedirectPage({ ctx }) {
  const router = useRouter()
  // Make sure we're in the browser
  if (typeof window !== 'undefined') {
    router.push('/home');
    return; 
  }
}

RedirectPage.getInitialProps = ctx => {
  // We check for ctx.res to make sure we're on the server.
  if (ctx.res) {
    ctx.res.writeHead(302, { Location: '/home' });
    ctx.res.end();
  }
  return { };
}

export default RedirectPage
票数 1
EN
查看全部 5 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63082929

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档