繁体   English   中英

将 nextjs 中的异步数据传递给页面的正确方法

[英]Proper way of passing asynchronous data in nextjs to pages

当前目录设置:

- components
    - NavBar
    - Header
    - Layout
- pages
    - pages
        - demo.js
- _app.js
- index.js
// index.js
import React from 'react';
import NewLayout from "../../components/NewLayout/NewLayout.js";
import $nacelle from '../../services/nacelle';

const Index = ({page}) => (
    <>
        <NewLayout header={page} />
        <pre>{JSON.stringify(page.id, null, 2)}</pre>
    </>
);

export async function getStaticProps({ context }) {
    try {
        const page = await $nacelle.data.content({
        handle: 'header_us_retail',
        type: 'header'
      });
    
        return {
          props: { page }
        };
    } catch {
        // do something useful if it doesnt work
        const page = 'failed';
        return {
          props: { page }
        };
    }
}

export default Index;

我正在将 Layout 导入 index.js 文件,加载异步数据并将其作为道具传递给布局,然后将用于呈现标题和导航栏(由布局组件导入)。 这在索引文件中按预期工作,但是我希望在 demo.js 文件和我在页面或其他地方创建的任何其他文件中使用相同的功能。 最有可能的问题是我如何尝试使用 Nextjs 和 React(两者都是新手),任何帮助将不胜感激。

原来问题在于 Nacelle 如何访问环境变量,而不是 NextJS 或 React 问题。

根据开发人员的说法,有多种方法可以公开环境变量,以下方法解决了我的特定问题:

// file in root: next.config.js
module.exports = {
  env: {
    NACELLE_SPACE_ID: process.env.NACELLE_SPACE_ID,
    NACELLE_GRAPHQL_TOKEN: process.env.NACELLE_GRAPHQL_TOKEN,
    NACELLE_ENDPOINT: process.env.NACELLE_ENDPOINT,
  },
};

暂无
暂无

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

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