Skip to content

Next.js 在两个页面中保存组件状态

效果预览

页面跳转了, 但 input 中的 state 在页面中被保存

Next.js App router目录结构

  • Directorymy-page/
    • Directorymy-page-1/
      • page.tsx
    • Directorymy-page-2/
      • page.tsx
    • layout.tsx 在此文件中创建上下文
    • page.tsx

Layout.tsx 中创建上下文

layout.tsx
"use client"
import { useState } from "react"
import { createContext } from "react";
import { MyLinkButton } from "@/components/ui/my-link-button"
export const MyPageContext = createContext({
inputValue: "this is a test",
setInputValue: () => { }
});
export default function DashboardLayout({
children,
}: {
children: React.ReactNode
}) {
const [inputValue, setInputValue] = useState("this is a test")
return <section>
<div className="container mt-7 flex gap-3 justify-center">
<MyLinkButton href="/my-page/my-page-1">
My Page 1
</MyLinkButton>
<MyLinkButton href="/my-page/my-page-2">
My Page 2
</MyLinkButton>
</div>
<MyPageContext.Provider value={{ inputValue, setInputValue }}>
{children}
</MyPageContext.Provider>
</section>
}

my-page-1/page.tsx 中使用上下文保存的 state

my-page-1/page.tsx
"use client"
import { useContext } from "react";
import { MyPageContext } from '../layout';
import { Input } from "@/components/ui/input";
export default function Page() {
const { inputValue, setInputValue } = useContext(MyPageContext);
const handleChange = (event:any) => {
setInputValue(event.target.value);
};
return <div className="container">
<p className="mb-5 text-green-500">MY Page 1</p>
<Input type="text" value={inputValue} onChange={handleChange} ></Input>
输入框中的 state 在页面中跳转中保存
</div>
}

my-page-2/page.tsx 中使用上下文保存的 state

my-page-2/page.tsx
"use client"
import { useContext } from "react";
import { MyPageContext } from '../layout';
import { Input } from "@/components/ui/input";
export default function Page() {
const { inputValue, setInputValue } = useContext(MyPageContext);
const handleChange = (event:any) => {
setInputValue(event.target.value);
};
return <div className="container">
<p className="mb-5 text-red-500">MY Page 2</p>
<Input type="text" value={inputValue} onChange={handleChange} ></Input>
输入框中的 state 在页面中跳转中保存
</div>
}