【问题标题】:Use nextRouter in getInitialProps在 getInitialProps 中使用 nextRouter
【发布时间】:2020-04-18 14:39:06
【问题描述】:

有什么方法可以在 nextjs getInitialProps 函数中使用或访问 nextRouter/history。

const ViewPost: NextPage<EditPostProps> = (props): React.ReactElement<void> => {
  const router = useRouter(); // works here 

}

ViewPost.getInitialProps = async (ctx: Context): Promise<EditPostProps> => {
  const router = useRouter(); // doesn't work 
  // ctx props doesn't have history
}
export default withRouter(ViewPost);

我的 api 类接收历史记录或路由器作为参数,因此需要一个,但我无法访问 getInitialProps 中的一个。请问无论如何我可以访问它吗?任何帮助将不胜感激。

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    next/router 是客户端路由器,因此在getInitialProps 中的服务器端渲染期间无法访问。

    由于 Next.js 9.3 getInitialProps 不推荐使用。

    您可以在getServerSideProps 内的服务器端重定向用户:

    import { GetServerSideProps } from 'next'
    
    export const getServerSideProps: GetServerSideProps = async context => {
        context.res.writeHead(302, { Location: '/login' })
        context.res.end()
        return {props: {}}
    }
    

    响应 (context.res) 是 Node.js http.ServerResponse 类的一个实例。

    GetServerSideProps

    http.ServerResponse

    How to redirect user's browser URL to a different page in Nodejs?

    【讨论】:

    • 我需要一个的原因是,到目前为止,我的 api 设计有一个备用方案,以防出错或未经身份验证的访问将用户重定向到登录页面。在正常反应中,我只需使用 creatBrowserHistory() 即可使用 history.push。我在 nextjs 中找不到等价物。在我看来,我不能在 nextjs 中使用历史记录或路由器外部组件,因此我想通过它。
    • @NuruSalihu,您可以使用ctx.res 对象重定向用户或在getInitialProps 内给出任何响应,因此您不需要客户端路由器
    • 你的意思是我可以重定向到某个路由,比如使用 ctx.res 登录?你能举个例子或进一步解释吗?谢谢?
    • 您的代码产生了错误 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client 。否则会很完美。
    • @NuruSalihu,试试getServerSideProps。查看更新的答案,我刚刚测试过它 - 它有效。
    【解决方案2】:

    路由器是单例的。你可以这样做:

    import Router from 'next/router'
    

    然后在getInitialProps()

    Router.push('/path');
    

    【讨论】:

      猜你喜欢
      • 2020-12-27
      • 2021-04-03
      • 2022-11-13
      • 1970-01-01
      • 2021-01-13
      • 2020-03-07
      • 2018-09-30
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多