如何在 nextjs 中导航而不丢失标题组件的状态 [英] How to navigate in nextjs without losing state of header component

查看:34
本文介绍了如何在 nextjs 中导航而不丢失标题组件的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以在不丢失标题组件状态的情况下创建/构造 next.js 应用程序以进行导航?

Is there any way how to create/structure next.js app for navigation without losing header component state?

让我解释一下.

我有这样的标题组件:


import { useState } from "react"
import Link from 'next/link'

export const Header = () => {
  const [value, setValue] = useState(1)

  return (
    <header>
      HEADER
      <button onClick={() => setValue(value + 1)}>
        {value}
      </button>
      <ul>
        <li>
          <Link href="/">
            <a>Home</a>
          </Link>
        </li>
        <li>
          <Link href="/test">
            <a>About Us</a>
          </Link>
        </li>
      </ul>
    </header>
  )
}

export default Header

有一个简单的计算机.

我有两页.索引:

const Home = () => (
  <div className="container">
    <Header />
    <main>
      Index
    </main>
  </div>
)

测试:

import Head from 'next/head'
import Header from '../components/header'

const Home = () => (
  <div className="container">
    <Header />
    <main>
      Test
    </main>
  </div>
)

export default Home

我想在此页面之间导航而不会丢失状态 i 标题组件.有可能,怎么做?

I would like to navigate between this pages without losing state i header component. It is possible and how?

推荐答案

您可以做的一件事是将整个 Next.js 应用程序包装在一个布局组件中,该组件包括 <Header/>.查看我创建的这个沙箱,看看如何将此模式应用于您问题中的示例:

One thing you can do is to wrap your entire Next.js app in a layout component which includes the <Header/>. Check out this sandbox I created to see how this pattern can be applied to the example in your question:

https://codesandbox.io/s/so-q-63755826-b-forked-7xt6u

查看这篇很棒的文章,它解释了这种模式以及在 Next.js 中持久化布局的其他一些解决方案:

Check out this great article which explains this pattern as well as some other solutions for persisting layout in Next.js:

https://adamwathan.me/2019/10/17/persistent-layout-patterns-in-nextjs/

这篇关于如何在 nextjs 中导航而不丢失标题组件的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆