Nextjs9中在_app.js入口使用getInitialProps请求数据,在传给子组件使用,解决导航栏全局在客户端渲染闪烁的问题.我这是用的class 组件的方式的,入口文件是这样的
function MyApp({ Component, pageProps,store,navData}) {}
如下,注意这里不同于页面级组件 使用
return {
props: {
authStates: authState,
data1,
data2,
data3
},
};
而是直接反射出去. 如下
MyApp.getInitialProps = async ({ctx}) => {
let postData = {
requestName:"P_PRODUCT_CATEGORY"
}
let result = await $fetch('post',P_PRODUCT_CATEGORY,postData)
let res = await result; //必须通过此方法才可返回数据
const navData = res.data;
return {
navData,
};
};
使用的时候也是直接
function MyApp({ Component, pageProps,store,navData}) {}
把之前的变量加进去, 就可以视图使用了.
function MyApp({ Component, pageProps,store,navData}) {
return <Provider store={store}>
<div className={`containers`}>
<Headers data={navData}/>
<Component {...pageProps} />
</div>
</Provider>
}
下面是完整的:
import { useCookie } from 'next-cookie'
import React,{ useState } from 'react';
import Head from 'next/head'
import {Provider} from 'react-redux';
import createWrapper from "next-redux-wrapper";
import store from '../redux/store';
import Router from "next/router";
/**header**/
import Headers from '../components/headers'
import Footer from '../components/footers'
import {$fetch, $fetch_serve} from "../serve";
import {P_BANNER, P_PRODUCT, P_PRODUCT_CATEGORY} from "../config/api";
import {parse,serialize} from "cookie";
import * as $Tool from "../util/tool";
import { setProductCategory } from '../redux/actions/counterActions.js';
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import cookie from "react-cookies";
if (typeof window !== 'undefined') {
require('../public/static/js/tool.js');
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/service-worker.js");
});
}
}
function MyApp({ Component, pageProps,store,navData}) {
return <Provider store={store}>
<>
<noscript type="text/html" dangerouslySetInnerHTML={{__html:notscrit}}/>
</>
<div className={`containers`}>
<Head>
<html lang="ja" />
<title>test</title>
<meta data-n-head={`ssr`} httpEquiv="Content-Language" content="en" />
<meta data-n-head={`ssr`} charSet={`utf-8`}/>
<meta data-n-head={`ssr`} name="author" content="Our team"/>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<script
type="module"
src="/static/js/custom.js"
/>
</Head>
<Headers data={navData}/>
<Component {...pageProps} />
</div>
</Provider>
}
//makeStore function that returns a new store for every request
const makeStore = () => store;
MyApp.getInitialProps = async ({ctx}) => {
let postData = {
requestName:"P_PRODUCT_CATEGORY"
}
let result = await $fetch('post',P_PRODUCT_CATEGORY,postData)
let res = await result; //必须通过此方法才可返回数据
const navData = res.data;
store.dispatch(setProductCategory(res.data));
if(ctx.req){
let Cookies ={};
if (ctx.req.headers.cookie != null) {
ctx.req.headers.cookie.split(';').forEach(l => {
var parts = l.split('=');
Cookies[parts[0].trim()] = (parts[1] || '').trim();
});
}
let userinfo = decodeURIComponent(Cookies.U_S)
userinfo = userinfo!=='undefined' && userinfo!==''?JSON.parse(userinfo):{}
const whiteList = ['/collections','/accountsettings','/notificationSettings','/activity','/orderList','/shoppingcart','/shoppingcart/payment','/shoppingcart/success'] // 路由需要登录白名单
if (whiteList.indexOf(ctx.asPath) !== -1) { // 在需要登录白名单中 // 需要登录权限进入的路由
if(userinfo.user_id){
}else {
if (ctx.res && ctx.asPath !== "/login") {
if(ctx.req.headers.referer.indexOf('/login') != -1){
ctx.res.setHeader('Location', `/login`);
} else {
ctx.res.setHeader('Location', `/login?from=${ctx.req.headers.referer}`);
}
ctx.res.statusCode = 302;
ctx.res.end();
}
}
}
if(userinfo.user_id){
if (ctx.res && ctx.asPath === "/login") {
ctx.res.setHeader('Location', '/home');
ctx.res.statusCode = 302;
ctx.res.end();
}
}
}
return {
navData,
};
};
//withRedux wrapper that passes the store to the App Component
export default createWrapper(makeStore)(MyApp);
完..