我是 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>
嗨,这是在所有情况下都可以使用的示例组件:
Vulcan下一个具有私有访问权限的启动器
这里的用法示例
答案是巨大的,很抱歉,如果我以某种方式违反了SO规则,但是我不想粘贴180行代码。如果要同时支持SSR和静态导出,则在Next中没有简单的模式来处理重定向。
以下场景分别需要一种特定的模式:
在撰写本文时(Next 9.4),您必须使用getInitialProps而不是getServerSideProps,否则您将失去做事的能力next export。
getInitialProps
getServerSideProps
next export
这些with-cookie-auth示例在中重定向getInitialProps。我不确定这是否是有效的模式,但这是代码:
with-cookie-auth
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令牌的调用,您可能希望将其封装到一个单独的函数中。
fetch
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的新问题