【问题标题】:Next.js Where to add Initial call to retrieve the user profileNext.js 在哪里添加初始调用以检索用户配置文件
【发布时间】:2020-02-07 21:17:52
【问题描述】:

我有一个 next.js 应用程序。 在初始化时,我需要调用一个操作来检索用户并将其设置为状态。 这应该只发生一次,并且只在应用程序启动时发生(可能只是服务器端)。 这样做的正确位置在哪里?

【问题讨论】:

    标签: next.js


    【解决方案1】:

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

    在 app.js 中

        static async getInitialProps({ Component }) {
    .
    .
    if(!process.browser)
    {
    ... make your calls here
    let results = data
    }
    

    将 API 调用的结果附加到 ...appProps

    appProps.serverData = results
    

    并返回 ...appProps

    您可以将服务器数据值设置为上下文提供程序,也可以将其设置在应用程序状态中。上下文将使状态值可以在其他页面中访问,您可以克服道具钻探。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-09
      • 1970-01-01
      • 1970-01-01
      • 2017-11-16
      • 2012-08-23
      • 2019-07-01
      • 2017-10-19
      相关资源
      最近更新 更多