小编典典

Next.js从/重定向到另一个页面

reactjs

我是 Next.js的新手, 并且想知道如何从起始页( / )重定向到 / hello-nextjs
。用户加载页面后,确定路径是否=== / 重定向至 / hello-nextjs

react-router中, 我们执行以下操作:

<Switch>
  <Route path="/hello-nextjs" exact component={HelloNextjs} />
  <Redirect to="/hello-nextjs" /> // or <Route path="/" exact render={() => <Redirect to="/hello-nextjs" />} />
</Switch>

阅读 1764

收藏
2020-07-22

共1个答案

小编典典

下一个9.4答案

嗨,这是在所有情况下都可以使用的示例组件:

Vulcan下一个具有私有访问权限的启动器

这里的用法示例

答案是巨大的,很抱歉,如果我以某种方式违反了SO规则,但是我不想粘贴180行代码。如果要同时支持SSR和静态导出,则在Next中没有简单的模式来处理重定向。

以下场景分别需要一种特定的模式:

  • 服务器端渲染:如果允许,我们渲染页面,如果不允许,则HTTP重定向
  • 静态渲染(服务器端):我们什么也不渲染,但是我们仍将页面包含在构建中
  • 静态导出后的客户端渲染:我们检查客户端是否为auth,以及是否重定向。在此检查或重定向过程中,我们不显示任何内容(或加载程序)。
  • 客户端使用next / router重定向后的客户端呈现:相同的行为。
  • SSR之后的客户端渲染:我们直接通过getInitialProps传递的prop来判断是否允许用户。它只是快一点,避免了空白闪光。

在撰写本文时(Next
9.4),您必须使用getInitialProps而不是getServerSideProps,否则您将失去做事的能力next export

旧答案(可行,但会有混乱的静态渲染)

半官方的例子

这些with-cookie-auth示例在中重定向getInitialProps。我不确定这是否是有效的模式,但这是代码:

Profile.getInitialProps = async ctx => {
  const { token } = nextCookie(ctx)
  const apiUrl = getHost(ctx.req) + '/api/profile'

  const redirectOnError = () =>
    typeof window !== 'undefined'
      ? Router.push('/login')
      : ctx.res.writeHead(302, { Location: '/login' }).end()

  try {
    const response = await fetch(apiUrl, {
      credentials: 'include',
      headers: {
        Authorization: JSON.stringify({ token }),
      },
    })

    if (response.ok) {
      const js = await response.json()
      console.log('js', js)
      return js
    } else {
      // https://github.com/developit/unfetch#caveats
      return await redirectOnError()
    }
  } catch (error) {
    // Implementation or Network error
    return redirectOnError()
  }
}

它同时处理服务器端和客户端。该fetch调用实际上是获得auth令牌的调用,您可能希望将其封装到一个单独的函数中。

我会建议

1.在服务器端渲染上重定向(避免在SSR期间使用Flash)

这是最常见的情况。您要在此时进行重定向以避免初始页面在首次加载时闪烁。

MyApp.getInitialProps = async appContext => {
    const currentUser = await getCurrentUser(); // define this beforehand
    const appProps = await App.getInitialProps(appContext);
    // check that we are in SSR mode (NOT static and NOT client-side)
    if (typeof window === "undefined" && appContext.ctx.res.writeHead) {
      if (!currentUser && !isPublicRoute(appContext.router.pathname)) {
          appContext.ctx.res.writeHead(302, { Location: "/account/login" });
          appContext.ctx.res.end();
      }
    }
    return { ...appProps, currentUser };
  };

2.在componentDidMount中重定向(在禁用SSR(例如在静态模式下)时很有用)

这是客户端渲染的后备。

  componentDidMount() {
    const { currentUser, router } = this.props;
    if (!currentUser && !isPublicRoute(router.pathname)) {
      Router.push("/account/login");
    }
  }

我无法避免以静态模式刷新初始页面,请添加这一点,因为您无法在静态构建过程中进行重定向,但它似乎比通常的方法要好。我会在取得进展时尝试进行编辑。

完整的例子在这里

相关问题,可悲的是最终只能由客户回答

我已打开有关redirecton的新问题

2020-07-22