【问题标题】:Next.js won't pass user prop in _app.tsxNext.js 不会在 _app.tsx 中传递用户属性
【发布时间】:2021-08-27 09:20:05
【问题描述】:

我想将用户对象传递给我的 next.js 应用程序中的所有页面。我没有将任何内容写入控制台或使用以下代码作为道具传递。放大部分似乎正在工作。

// _app.tsx

import type { AppProps } from "next/app"
import type { GetServerSideProps, GetServerSidePropsContext } from "next"
import Amplify, { Auth, withSSRContext } from "aws-amplify"
import { AmplifyAuthenticator, AmplifySignIn } from "@aws-amplify/ui-react"
import { config } from "../amplify.config"

Amplify.configure({ ...config, ssr: true })

MyApp.getServerSideProps = async (context: GetServerSidePropsContext) => {
    const appProps = await getServerSideProps(context)

    return { ...appProps }
}

export const getServerSideProps: GetServerSideProps = async (ctx) => {
    const auth = withSSRContext(ctx).Auth as typeof Auth

    let user: any
    try {
        user = await auth.currentAuthenticatedUser()
        console.log("user is authenticated:", user)
        return { props: { user: user } }
    } catch (err) {
        console.log("error: no authenticated user")
    }
}

export default function MyApp({ Component, pageProps }: AppProps) {
    return (
        <AmplifyAuthenticator>
            <AmplifySignIn hideSignUp usernameAlias="email" slot="sign-in" />
            <Component {...pageProps} />
        </AmplifyAuthenticator>
    )
}

【问题讨论】:

  • Next.js 中的自定义 _app 不支持 getServerSideProps 和 getStaticProps。尝试改用 getInitiapProps。
  • 我遇到了类似的问题。 getInitialProps 将起作用,但会导致您的应用程序在服务器端呈现每个页面。 nextjs.org/docs/advanced-features/custom-app#caveats

标签: typescript next.js server-side-rendering aws-amplify react-props


【解决方案1】:

请阅读next.js的这部分文档

https://nextjs.org/docs/advanced-features/custom-app

应用目前不支持 Next.js 数据获取方法,例如 getStaticProps 或 getServerSideProps。

因此,您必须在 _app.js 中进行一些更改才能实现这一目标。

您可以在这篇文章中找到解决方案: Next.js: Reduce data fetching and share data between pages

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-14
    • 2017-05-04
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2020-02-28
    相关资源
    最近更新 更多