繁体   English   中英

将数据(prop)从 _app.js 传递到页面中的 getServerSideProps - NextJS,最新版本

[英]Pass data (prop) from _app.js to getServerSideProps in a page - NextJS, latest version

我有一个自定义_app.js

  const Layout = ({ children }) => (children);

  const app = ({ Component, pageProps }) => {

    pageProps.baseUrl = 'some url';

    return (
      <Layout>
        <Component {...pageProps} />
      </Layout>
    )
};

还有一个页面:

export async function getServerSideProps({ req, query, res, baseUrl }) { 
// baseUrl is undefined and an error, if I am using it with destructiring

  console.log(req) // There is no baseUrl

  return { props: { ..... } }
}

我想设置pageProps.baseUrl= 'some url'; _app.js中并在包括getServerSideProps在内的页面组件中使用它,我该怎么做?

现在,我创建了一个文件,其中包含所有全局值,如下所示:

let store = {};

const globalStore = {};

globalStore.set = (key, value) => {
    store = { ...store, [key]: value };
}

globalStore.get = (key) => {
    return store[key];
}


export default globalStore;

然后在_app.js中导入它并设置一个值:

const app = ({ Component, pageProps }) => {
    globalStore.set('baseUrl', 'some url 1');
    globalStore.set('baseUrl2', 'some url 2');

    return (
        <Layout>
            <Component {...pageProps} />
        </Layout>
    )
}

pages/index.js和组件或getServerSideProps中导入文件:

export async function getServerSideProps({ req, query, res }) {

    console.log('in getServerSideProps');
    console.log(globalStore.get('baseUrl'));
    console.log(globalStore.get('baseUrl2'));
...

我认为,在这种特殊情况下,可以在这里使用常量而不是道具。

建议的解决方案

在常量.js 中:

export const BASE_URL = 'some url';

在您的页面中:

import * as Constants from '../path/to/constants';

export async function getServerSideProps({ req, query, res }) { 
  // use Constants.BASE_URL here

  return { props: { ..... } }
}

为什么道具不能按照您希望的方式工作?

您的页面组件和您从文件中导出的 getServerSideProps 方法是分开的,并且在不同的时间执行。 渲染组件不会调用 getServerSideProps。 我相信 Next.js 中的顺序是这样的:

  1. 在路由上发出请求。
  2. Next.js 查看pages/中的文件寻找对应的路由
  3. Next.js 将根据执行上下文运行适当的方法(在服务器渲染上,getServerSideProps)
  4. Next.js 渲染 App 组件,将 getServerSideProps 提供的 pageProps 传递给它
  5. App 组件渲染 Page 组件

在这种情况下,你创造了一个悖论。 想想道具是如何流动的:

  1. getServerSideProps 运行,返回一个 pageProps object
  2. 应用组件渲染,包含从 getServerSideProps 传递的 pageProps object
  3. 页面组件渲染,传递了 pageProps

如果 getServerSideProps 负责创建 pageProps object,也不能将 object 作为参数传递。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM