簡體   English   中英

我可以在 _app.js 和頁面中使用 getInitialProps 嗎?

[英]Can I use getInitialProps in _app.js and in pages?

我正在開發我的第一個嚴肅的 NextJS 應用程序。 我已將其設置為為左側導航提取 JSON 數據,而不是將它們硬編碼在應用程序中的某處。 這樣我就不必在每次對站點導航進行細微更改時都重新構建。

由於導航需要在每個頁面上都可用,因此我將getInitialProps添加到_app.js文件中,該文件抓取左側導航並將其傳遞給左側導航組件。 但是現在當我繼續構建主頁時,我發現那里的getInitialProps沒有運行。 似乎_app.js中的getInitialProps優先。

有沒有辦法兩者兼得? 或者其他一些實現目標的解決方法(或者只是一種更好的方法)?

請注意,我使用getInitialProps有兩個原因:

  1. getStaticProps 已出局,因為我不打算在構建時構建整個站點
  2. getServerSideProps通常不可用,因為我不喜歡它最終執行兩個 http 請求:首先一個請求發送到NextJS服務器,然后服務器發送一個請求到我的 API(它恰好位於不同的服務器上)。 如果我只是獲得導航之類的基本內容,則無需在NextJS服務器上運行getServerSideProps ,我寧願跳過中間人

下面是一些簡化的代碼:

_app.js :

import { Provider } from "react-redux";
import axios from "axios";

import store from "../store";
import Header from "../components/Header";
import LeftNav from "../components/LeftNav";

function MyApp(props) {
    const { Component, pageProps } = props;

    return (
        <Provider store={store}>
            <Header />
            <LeftNav leftnav={props.leftnav} />
            <Component { ...pageProps } />
        </Provider>
    )
}

MyApp.getInitialProps = async (context) => {
    let config = await import("../config/config");
    let response = await axios.get(`${config.default.apiEndpoint}&cAction=getLeftNav`);

    if (response) {
        return {
            leftnav: response.data.leftNav
        };
    } else {
        return {
            leftnav: null
        };
    }
};

export default MyApp;

主頁.js :

import axios from "axios";

const Home = (props) => {
    console.log("Home props", props);
    return (
        <div>home</div>
    );
};

Home.getInitialProps = async(context) => {
    
    // this only runs if the getInitialProps in _app.js is removed :(

    let config = await import("../config/config");
    let response = await axios.get( `${config.default.apiEndpoint}&cAction=getHome` );
    if ( response ) {
        return {
            home: response.data.home
        };
    } else {
        return {
            home: null
        }
    }
};
export default Home;

你必須調用App.getInitialProps(context)_app調用當前頁面的getInitialProps 然后,您可以將頁面的道具與來自_app的其余道具_app

import App from 'next/app'

// Remaining code...

MyApp.getInitialProps = async (context) => {
    const pageProps = await App.getInitialProps(context); // Retrieves page's `getInitialProps`
    
    let config = await import("../config/config");
    let response = await axios.get(`${config.default.apiEndpoint}&cAction=getLeftNav`);

    return {
        ...pageProps,
        leftnav: response?.data?.leftNav ?? null
    };
};

來自自定義_app文檔:

當您在自定義應用程序中添加getInitialProps時,您必須import App from "next/app"getInitialProps調用App.getInitialProps(appContext)並將返回的對象合並到返回值中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM