Nextjs - 将道具从自定义 _app.js 传递到 <Navbar> 组件?

Zak*_*ria 5 javascript reactjs next.js react-props

如何将道具从这里传递到要添加到 Head 组件下的导航栏组件?我已经使用 getServerSideProps 在 index.js 页面中完成了此操作,但它似乎在 _app.js 文件中不起作用。

import "../_app.css";

import React from "react";
import PropTypes from "prop-types";
import Head from "next/head";
import { ThemeProvider } from "@material-ui/core/styles";
import CssBaseline from "@material-ui/core/CssBaseline";
import theme from "../theme";

export default function MyApp({ Component, pageProps }) {
    React.useEffect(() => {
        // Remove the server-side injected CSS.
        const jssStyles = document.querySelector("#jss-server-side");
        if (jssStyles) {
            jssStyles.parentElement.removeChild(jssStyles);
        }
    }, []);

    return (
        <React.Fragment>
            <Head>
                <title>Furnibnz | Baldai Internetu ir Nemokamas Pristatymas</title>
                <meta
                    name="viewport"
                    content="minimum-scale=1, initial-scale=1, width=device-width"
                />
            </Head>
            <ThemeProvider theme={theme}>
                {/* CssBaseline kickstart an elegant, consistent, and simple baseline to build upon. */}
                <CssBaseline />
                <Component {...pageProps} />
            </ThemeProvider>
        </React.Fragment>
    );
}

MyApp.propTypes = {
    Component: PropTypes.elementType.isRequired,
    pageProps: PropTypes.object.isRequired,
};
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法在每个页面中使用导航栏组件,或者这是正确的方法吗?

Zak*_*ria 2

当这是我最大的问题时的美好时光哈哈

对于真正需要答案的人:

您当前无法在 _app 组件中使用 getStaticProps 和 getServerSideProps ,因此,如果我没记错的话,我会尝试获取初始数据(可能是类别列表)并将其传递给组件。要在 _app 级别获取初始数据,您应该使用 getInitialProps(NextJs 开发人员建议避免使用它),但请注意,使用它会阻止 NextJs 自动静态优化不依赖于任何类型获取方法的页面(它们将在服务器端呈现 - 即使是一个简单的“关于我们”页面,也可以作为静态 html 提供)

您可以在这里阅读更多相关信息:https://nextjs.org/docs/api-reference/data-fetching/getInitialProps