Next.js 中的条件重定向 [英] Conditional redirection in Next.js
问题描述
是否可以根据 cookie 值有条件地将用户重定向到另一个 Url?我知道我可以检查服务器上的 cookie &然后重定向.但是如果用户是通过 Link
来的,我该怎么办.(我不能使用 Route.push 因为它在服务器上未定义)有没有办法只在浏览器上使用Router?
Is it possible to conditionally redirect a user to another Url based on cookie value?
I know I can inspect cookie on a server & then redirect.
But what should I do if a user came through Link
. (I can't use Route.push because it's undefined on the server)
Is there any way to use Router only on the browser?
我至少知道一种方法:创建简单的 button
并添加 Router push &检查 onClick
处理程序中的 cookie,但这是正确的方法吗?
I know at least one way to do this: to create simple button
and add Router push & check cookies inside onClick
handler, but is it a correct way to do this?
推荐答案
你可以检查用户是通过服务器还是客户端访问了页面.之后,您可以使用适当的工具有条件地重定向.getInitialProps
函数获取 ctx
对象.您可以像这样检查它是在服务器上还是在客户端上:
you can check if user has accessed the page via server or client side.
and after that you can conditionally redirect with the proper tool.
getInitialProps
function gets a ctx
object. you can check whether its on server or client like this:
import Router from 'next/router'
export default class Browse extends Component {
static async getInitialProps (ctx) {
if (ctx && ctx.req) {
console.log('server side')
ctx.res.writeHead(302, {Location: `/`})
ctx.res.end()
} else {
console.log('client side')
Router.push(`/`)
}
...
这篇关于Next.js 中的条件重定向的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!