Next.js 获取和维护所有组件的全局数据

Jay*_*nth 8 reactjs next.js react-component

在我的 Next.js 应用程序中,我需要进行一个 API 调用,该调用将返回一个所有组件都需要使用的 JSON 响应。因此,我将避免在我的组件中多次调用相同的 API。实现这一目标的正确方法是什么?

Ste*_*tti 16

取决于应用的范围。
如果它很大,你可能应该采用像 Redux 这样的状态管理器,正如 Moshin Amjad 所说。

如果它是一个较小的应用程序,您可以尝试使用 React 上下文 API 来管理它。
我将以最简单的方式举一个例子,使用功能组件,利用getStaticProps而不是getInitialProps为了获得静态生成的页面。

开始创建一个简单的上下文

libs/context.js

import React from "react";
export const Context = React.createContext();
Run Code Online (Sandbox Code Playgroud)

然后用来自 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
  }
}
Run Code Online (Sandbox Code Playgroud)

最后在提供者的任何子级中使用它(或更改它!)。

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>
   )
}
Run Code Online (Sandbox Code Playgroud)

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>
   )
}
Run Code Online (Sandbox Code Playgroud)

它未经测试,但你明白了。
最终,您可以将上下文提供程序移动到高阶组件中,以包装每个页面,或者甚至在pages/_app.js您需要更高级别的数据时。

请记住,如果应用程序向上扩展,您应该考虑使用 Redux 之类的东西。

  • 我需要同样的东西,但我认为如果用户的第一页不是根目录,这将不起作用 (5认同)
  • 不幸的是,这些方法否定了结果将在客户端处理的事实,因此对 SEO 不友好。 (2认同)