简体   繁体   English

static 页面中的动态导航栏内容

[英]Dynamic Navbar content in an otherwise static page

I have a navbar that changes its content depending on whether the user is signed in or not.我有一个导航栏,它根据用户是否登录来更改其内容。 I want to use getStaticProps to get the props for the rest of the page but this makes the navbar pre-rendered and if the user logs in it stays the same.我想使用 getStaticProps 获取页面 rest 的道具,但这会使导航栏预呈现,如果用户登录,它会保持不变。

The navbar is implemented in the _app page as it is shared between all the pages.导航栏在 _app 页面中实现,因为它在所有页面之间共享。

Here is my code:这是我的代码:

    function MyApp({ Component, pageProps, appProps }) {
  return (
    <React.Fragment>
      <Header
        links={
          <HeaderLinks user={appProps.user} />
        }
      />
        <Component {...pageProps} {...appProps} />
      <MyFooter />
    </React.Fragment>
  );
}

MyApp.getInitialProps = async ({ Component, ctx }) => {
  const { token } = parseCookies(ctx);
  let appProps = {};

  if (!token) {
    const isProtectedRoute =
      ctx.pathname === '/account' || ctx.pathname === '/create';
    if (isProtectedRoute) {
      redirectUser(ctx, '/login');
    }
  } else {
    try {
      const payload = { headers: { Authorization: token } };
      const url = `${baseUrl}/api/account`;
      const response = await axios.get(url, payload);
      const user = response.data;
      // if authenticated but not admin or root then redirect from the create page
      const isRoot = user.role === 'root';
      const isAdmin = user.role === 'admin';
      const isNotPermitted = !(isRoot || isAdmin) && ctx.pathname === '/create';
      if (isNotPermitted) {
        redirectUser(ctx, '/');
      }
      appProps.user = user;
    } catch (error) {
      console.error('Error getting current user', error);
      // delete invalid tokens
      destroyCookie(ctx, 'token');
      // redirect to login
      redirectUser(ctx, '/login');
    }
  }
  return { appProps };
};

export default MyApp;

I am wondering if there is any way I can make the content of the page statically generated using getStaticProps but the navbar props be dynamic so when the use logs in only the nav bar changes?我想知道是否有任何方法可以使用 getStaticProps 静态生成页面内容,但导航栏道具是动态的,因此当使用日志时,只有导航栏发生变化?

Import the navbar as a dynamic import with ssr:false this means the client will only import/execute it.使用ssr:false将导航栏导入为动态导入,这意味着客户端将只导入/执行它。

const NavBar = dynamic( () => import('../components/NavBar'), 
{ ssr: false } )
// ... Rest of your statically generated page 

More here: https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr更多信息: https://nextjs.org/docs/advanced-features/dynamic-import#with-no-ssr

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

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