【问题标题】:Conditional redirection in Next.jsNext.js 中的条件重定向
【发布时间】:2017-12-19 08:15:22
【问题描述】:

是否可以根据 cookie 值有条件地将用户重定向到另一个 Url? 我知道我可以检查服务器上的 cookie 然后重定向。 但是如果用户通过Link 来我该怎么办。 (我不能使用 Route.push 因为它在服务器上未定义) 有没有办法只在浏览器上使用Router?

我至少知道一种方法:创建简单的 button 并在 onClick 处理程序中添加路由器推送和检查 cookie,但这是正确的方法吗?

【问题讨论】:

    标签: javascript reactjs server-side-rendering nextjs


    【解决方案1】:

    您可以检查用户是否通过服务器或客户端访问了该页面。 之后,您可以使用适当的工具有条件地重定向。 getInitialProps 函数获取 ctx 对象。您可以像这样检查它是在服务器上还是在客户端上:

    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(`/`)
            }
    ...
    

    【讨论】:

    • 避免 301,除非你很确定。使用 302 进行临时移动。
    猜你喜欢
    • 2021-04-10
    • 1970-01-01
    • 2021-10-31
    • 2012-02-04
    • 2012-01-09
    • 2012-01-14
    • 1970-01-01
    • 2021-10-09
    • 2023-04-03
    相关资源
    最近更新 更多