[英]Can I use getInitialProps in _app.js and in pages?
我正在開發我的第一個嚴肅的 NextJS 應用程序。 我已將其設置為為左側導航提取 JSON 數據,而不是將它們硬編碼在應用程序中的某處。 這樣我就不必在每次對站點導航進行細微更改時都重新構建。
由於導航需要在每個頁面上都可用,因此我將getInitialProps
添加到_app.js
文件中,該文件抓取左側導航並將其傳遞給左側導航組件。 但是現在當我繼續構建主頁時,我發現那里的getInitialProps
沒有運行。 似乎_app.js
中的getInitialProps
優先。
有沒有辦法兩者兼得? 或者其他一些實現目標的解決方法(或者只是一種更好的方法)?
請注意,我使用getInitialProps
有兩個原因:
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.