Art*_*hur 55 html routing reactjs react-router next.js
我是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>
Run Code Online (Sandbox Code Playgroud)
Nic*_*ani 77
编辑:Next.js >= 10
从 Next.js 10 开始,您可以使用内部的键或进行服务器端重定向(请参阅下面的客户端重定向):redirect
getServerSideProps
getStaticProps
export async function getServerSideProps(context) {
const res = await fetch(`https://.../data`)
const data = await res.json()
// or use context.resolvedUrl for conditional redirect
// if(context.resolvedUrl == "/")
if (!data) {
return {
redirect: {
destination: '/hello-nextjs',
permanent: false,
},
}
}
return {
props: {}, // will be passed to the page component as props
}
}
Run Code Online (Sandbox Code Playgroud)
注意:使用getServerSideProps
将强制应用程序到 SSR,也不支持在构建时重定向,如果在构建时已知重定向,您可以在next.config.js 中添加这些
在next.js
您可以使用ex加载页面后重定向Router
:
import Router from 'next/router'
componentDidMount(){
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
}
Run Code Online (Sandbox Code Playgroud)
或者使用钩子:
import React, { useEffect } from "react";
import Router from 'next/router'
...
useEffect(() => {
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
});
Run Code Online (Sandbox Code Playgroud)
如果你想在重定向之前防止闪烁,你可以使用一个简单的技巧:
import React, { useEffect,useState } from "react";
import Router from 'next/router'
const myPage = ()=>{
const [loaded,setLoaded] = useState(false)
useEffect(() => {
const {pathname} = Router
// conditional redirect
if(pathname == '/' ){
// with router.push the page may be added to history
// the browser on history back will go back to this page and then forward again to the redirected page
// you can prevent this behaviour using location.replace
Router.push('/hello-nextjs')
//location.replace("/hello-nextjs")
}else{
setLoaded(true)
}
},[]);
if(!loaded){
return <div></div> //show nothing or a loader
}
return (
<p>
You will see this page only if pathname !== "/" , <br/>
</p>
)
}
export default myPage
Run Code Online (Sandbox Code Playgroud)
我会说,当您可以使用next.config.js
重定向甚至更好地使用组件的条件渲染时,通常不是进行客户端重定向的好/优雅方法。
我创建一个简单的回购与上面的例子都在这里。
Eri*_*rel 45
首先,您应该评估您是否需要客户端重定向(在 React 内)、服务器端重定向(301 HTTP 响应)或服务器端重定向 + 身份验证(301 HTTP 响应但也有一些逻辑来检查身份验证)。
这是我能写的最完整的答案。但是,在大多数情况下,您不需要任何这些。就像在任何 React 应用程序中一样重定向。首选客户端重定向。只需使用useEffect
+ router.push
,就是这样。
服务器端重定向很诱人,特别是当您想要“保护”私人页面时,但您应该评估您是否真的需要它们。通常,你不会。它们会带来意想不到的复杂性,例如管理身份验证令牌和刷新令牌。相反,您可能希望向您的体系结构添加网关服务器、反向代理或任何前端服务器,例如处理这些类型的检查。
请记住,Next.js 只是 React 应用程序,使用 Next.js 高级功能(如 SSR)需要付出代价,这在您的上下文中是合理的。
嗨,这是一个适用于所有场景的示例组件:
Vulcan next starter with Private access
答案是巨大的,很抱歉,如果我以某种方式违反了 SO 规则,但我不想粘贴 180 行代码。如果你想同时支持 SSR 和静态导出,在 Next 中没有简单的模式来处理重定向。
以下场景均需要特定模式:
在撰写本文时(Next 9.4),您必须使用getInitialProps
,而不是getServerSideProps
,否则您将失去执行 的能力next export
。
正如@Arthur 在评论中所述,9.5 还包括在 next.config.js 中设置重定向的可能性。我还不清楚这个功能的局限性,但它们似乎是全局重定向,例如,当您需要移动页面或仅允许在有限时间内访问时。因此,例如,它们不打算处理身份验证,因为它们似乎无权访问请求上下文。再次,有待确认。
此解决方案特定于取决于身份验证的重定向。
我不喜欢从 进行身份验证getServerSideProps
,因为在我看来为时已晚,并且很难设置高级模式,例如处理刷新令牌。但这是官方的解决方案。
您可能还想根据 Vercel 的仪表板的工作方式(在撰写本文时)检查此票证中记录的方法,以防止未经身份验证的内容闪烁
下一个 10.2 引入基于标头和 cookie 的重写。这是基于身份验证 cookie 或标头的存在重定向服务器端的好方法。
但是,请记住,这不是安全的重定向。用户可以使用虚假令牌更改他们的请求标头。您仍然需要网关、反向代理或前置服务器来实际检查令牌有效性并正确设置标头。
编辑:注意 URL 不会改变。重写将 URL 指向应用程序的现有页面,而无需更改 URL => 它允许您拥有“虚拟”URL。
用例示例:假设您有一个页面src/contact.tsx
,已翻译,并设置了 i18n 重定向。您可以通过重写/de/kontact
为来翻译页面名称本身(“联系人”)/de/contact
。
该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()
}
}
Run Code Online (Sandbox Code Playgroud)
它处理服务器端和客户端。fetch
调用是实际获取身份验证令牌的调用,您可能希望将其封装到一个单独的函数中。
这是最常见的情况。此时您想重定向以避免初始页面在首次加载时闪烁。
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()
}
}
Run Code Online (Sandbox Code Playgroud)
这是客户端渲染的回退。
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 };
};
Run Code Online (Sandbox Code Playgroud)
我无法避免在静态模式下闪烁初始页面添加这一点,因为您无法在静态构建期间重定向,但它似乎比通常的方法更好。我会在取得进展时尝试编辑。
Afs*_*fda 30
有三种方法。
1.重定向事件或函数:
import Router from 'next/router';
<button type="button" onClick={() => Router.push('/myroute')} />
Run Code Online (Sandbox Code Playgroud)
2.使用钩子重定向:
import Router , {useRouter} from 'next/router';
const router = useRouter()
<button type="button" onClick={() => router.push('/myroute')} />
Run Code Online (Sandbox Code Playgroud)
3.使用链接重定向:
基于 Nextjs 文档,<a>
链接内的标签是必需的,例如在新标签页中打开!
import Link from 'next/link';
<Link href="/myroute">
<a>myroute</a>
</Link>
Run Code Online (Sandbox Code Playgroud)
服务器端路由还有一些其他选项,即asPath
. 在所有描述的方法中,您可以添加 asPath 来重定向客户端和服务器端。
Mar*_*oss 20
Next.js 10+ 为我们提供了一些额外且优雅的解决方案来进行重定向。
服务器端- 你应该使用getServerSideProps
下面的示例假设我们有一些额外的会话要检查(但可以是您想要的任何内容)。如果会话为空并且我们位于服务器端 ( context.res
),则意味着用户尚未登录,我们应该重定向到登录页面 ( /login
)。以另一种方式,我们可以传递session
并props
重定向到/dashboard
:
import { getSession } from 'next-auth/client';
export const getServerSideProps = async (context) => {
const session = await getSession(context);
if(context.res && !session) {
return {
redirect: {
permanent: false,
destination: '/login'
}
}
}
return {
props: { session },
redirect: {
permanent: false,
destination: '/dashboard'
}
}
}
Run Code Online (Sandbox Code Playgroud)
客户端- 您可以使用例如useRouter
钩子:
import { useRouter } from 'next/router';
import { useSession } from 'next-auth/client';
const router = useRouter();
const [ session, loading ] = useSession();
if (typeof window !== 'undefined' && loading) return null;
if (typeof window !== 'undefined' && !session) {
router.push('/login');
}
router.push('/dashboard');
Run Code Online (Sandbox Code Playgroud)
更多信息在这里:https ://github.com/vercel/next.js/discussions/14890
@Nico 的答案解决了您使用类时的问题。
如果您正在使用函数,则无法使用componentDidMount
. 相反,您可以使用 React Hooks useEffect
。
import React, {useEffect} from 'react';
export default function App() {
const classes = useStyles();
useEffect(() => {
const {pathname} = Router
if(pathname == '/' ){
Router.push('/templates/mainpage1')
}
}
, []);
return (
null
)
}
Run Code Online (Sandbox Code Playgroud)
2019 年,React引入了hooks。这比课堂更快、更高效。
在 NextJs v9.5 及更高版本中,您可以在next.config.js文件中配置重定向和重写。
但如果您正在使用,trailingSlash: true
请确保源路径以斜杠结尾,以便正确匹配。
module.exports = {
trailingSlash: true,
async redirects() {
return [
{
source: '/old/:slug/', // Notice the slash at the end
destination: '/new/:slug',
permanent: false,
},
]
},
}
Run Code Online (Sandbox Code Playgroud)
您还需要考虑可能影响路由的其他插件和配置,例如next-images。
文档: https: //nextjs.org/docs/api-reference/next.config.js/redirects
redirect-to.ts
import Router from "next/router";
export default function redirectTo(
destination: any,
{ res, status }: any = {}
): void {
if (res) {
res.writeHead(status || 302, { Location: destination });
res.end();
} else if (destination[0] === "/" && destination[1] !== "/") {
Router.push(destination);
} else {
window.location = destination;
}
}
Run Code Online (Sandbox Code Playgroud)
_app.tsx
import App, {AppContext} from 'next/app'
import Router from "next/router"
import React from 'react'
import redirectTo from "../utils/redirect-to"
export default class MyApp extends App {
public static async getInitialProps({Component, ctx}: AppContext): Promise<{pageProps: {}}> {
let pageProps = {};
if (Component.getInitialProps) {
pageProps = await Component.getInitialProps(ctx);
}
if (ctx.pathname === "" || ctx.pathname === "/_error") {
redirectTo("/hello-next-js", { res: ctx.res, status: 301 }); <== Redirect-To
return {pageProps};
}
return {pageProps};
}
render() {
const {Component, pageProps} = this.props;
return <Component {...pageProps}/>
}
}
Run Code Online (Sandbox Code Playgroud)
这里有 2 个复制粘贴级别的示例:一个用于浏览器,一个用于服务器。
https://dev.to/justincy/client-side-and-server-side-redirection-in-next-js-3ile
假设您想从根 (/) 重定向到名为 home 的页面:(/home)
在您的主索引文件中,粘贴以下内容:
客户端
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
Run Code Online (Sandbox Code Playgroud)
服务器端
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
Run Code Online (Sandbox Code Playgroud)
适用于 NextJS 9.5.0+
next.config.js
文件module.exports = {
async redirects() {
return [
{
source: '/team',
destination: '/about',
permanent: false,
},
{
source: "/blog",
destination:
"https://blog.dundermifflin.com",
permanent: true,
},
];
},
};
Run Code Online (Sandbox Code Playgroud)
https://github.com/vercel/next.js/tree/canary/examples/redirects
我通过定义一个根页面在我的应用程序中实现了此功能,Next.JS
该根页面执行重定向服务器端和客户端。这是根页面的代码:
import { useEffect } from "react";
import Router from "next/router";
const redirectTo = "/hello-nextjs";
const RootPage = () => {
useEffect(() => Router.push(redirectTo));
return null;
};
RootPage.getInitialProps = (ctx) => {
if (ctx.req) {
ctx.res.writeHead(302, { Location: redirectTo });
ctx.res.end();
}
};
export default RootPage;
Run Code Online (Sandbox Code Playgroud)
Next.js >= 12.1
重定向中不再允许使用相对 URL
Error: URLs is malformed. Please use only absolute URLs
,并且会抛出: 。
要使用Next.js >= 12.1 的中间件进行重定向:
middleware.ts
相同的级别创建一个(或 .js)文件pages
middleware
函数redirect
打字稿示例middleware.ts
:
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
const url = request.nextUrl.clone()
if (url.pathname === '/') {
url.pathname = '/hello-nextjs'
return NextResponse.redirect(url)
}
}
Run Code Online (Sandbox Code Playgroud)