html - 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>
解决方案
更新:Next.js >= 12
现在您可以使用中间件_middleware.js
进行重定向,在 pages 文件夹(或 pages 内的任何子文件夹)中创建一个文件
import { NextResponse, NextRequest } from 'next/server'
export async function middleware(req, ev) {
const { pathname } = req.nextUrl
if (pathname == '/') {
return NextResponse.redirect('/hello-nextjs')
}
return NextResponse.next()
}
更新:Next.js >= 10
从 Next.js 10 开始,您可以使用内部的键进行服务器端重定向(请参见下文的客户端重定向)or :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
}
}
注意:使用getServerSideProps
将强制应用程序进行 SSR,也不支持在构建时重定向,如果重定向在构建时已知,您可以在next.config.js中添加这些重定向
在next.js
您可以使用ex加载页面后重定向:Router
import Router from 'next/router'
componentDidMount(){
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
}
或使用 Hooks :
import React, { useEffect } from "react";
import Router from 'next/router'
...
useEffect(() => {
const {pathname} = Router
if(pathname == '/' ){
Router.push('/hello-nextjs')
}
});
如果你想在重定向之前防止闪烁,你可以使用一个简单的技巧:
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
我会说,当您可以使用next.config.js
重定向甚至更好地使用组件的条件渲染时,通常不是一个好的/优雅的客户端重定向方法。
我在这里创建了一个包含上面所有示例的简单存储库。
推荐阅读
- java - Spring Boot 不接受括号中的列表参数
- php - 如何在 PHP 中使用 preg_replace 将表达式替换为元字符?
- php - 第二个怎么来
- 标签在我的代码中破坏了 {},而第一个
- 标签和标签没问题?
- networking - 网络爬取时的网络优化 - 使用 udp 和使用连接池?
- quarkus - Quarkus 中的 ConversationScoped
- python - 在 Python 中从另一个函数调用变量
- python - SyntaxError:解析python错误消息时出现意外的EOF
- html - 如何根据调用的内容自行制作边框大小?
- xpath - 如何获取动态加载类的 xpath 选择器
- wordpress - 尝试访问我的 wordpress 网站时出现 Connection_time_out 错误 - 尝试了所有解决方案