取决于应用的范围。
如果它很大,你可能应该采用像 Redux 这样的状态管理器,正如 Moshin Amjad 所说。
如果它是一个较小的应用程序,您可以尝试使用 React 上下文 API 来管理它。
我将以最简单的方式举一个例子,使用功能组件,利用getStaticProps 而不是getInitialProps 来获取静态生成的页面。
开始创建一个简单的上下文
libs/context.js
import React from "react";
export const Context = React.createContext();
然后使用来自 getStaticProps(或 getInitialProps)的数据填充 useState 挂钩(或者更好的是,useReducer 取决于数据的结构),然后将其传递给上下文提供程序。
pages/index.js
import React from 'react'
import { Context } from "../libs/context.js"
import Title from "../components/Title"
import Button from "../components/Button"
// data will be populated at build time by getStaticProps()
function Page({ data }) {
const [ context, setContext ] = React.useState(data)
return (
<Context.Provider value={[context, setContext]}>
<main>
<Title />
<Button />
</main>
</Context.Provider>
)
}
export async function getStaticProps(context) {
// fetch data here
const data = await fetchData()
// Let's assume something silly like this:
// {
// buttonLabel: 'Click me to change the title',
// pageTitle: 'My page'
// }
return {
props: {
data
}, // will be passed to the page component as props
}
}
最后在提供者的任何孩子中使用它(或改变它!)。
components/Title.js
import React, { useContext } from "react"
import { Context } from "./Context"
export default function MyComponent() {
const [context, setContext] = useContext(Context)
return (
<h1>{context.pageTitle}</h1>
)
}
components/Button.js
import React, { useContext } from "react"
import { Context } from "./Context"
export default function MyComponent() {
const [context, setContext] = useContext(Context)
function changeTitle() {
preventDefault();
setContext(oldContext => ({
...oldContext,
pageTitle: 'New page title!'
}))
}
return (
<div>
<button onClick={changeTitle}>{context.buttonLabel}</button>
</div>
)
}
它未经测试,但你明白了。
最终,您可以将上下文提供程序移动到高阶组件中以包装每个页面,如果您需要更高级别的数据,甚至可以在 pages/_app.js 中。
请记住,如果应用程序扩展,您应该考虑使用 Redux 之类的东西。