【问题标题】:State Management in NextJSNextJS 中的状态管理
【发布时间】:2021-11-23 06:51:55
【问题描述】:

我已经在互联网上四处寻找解决方案,但我仍然没有找到有效的解决方案。我尝试了以下状态管理工具:

  • 使用上下文
  • Redux
  • Zustand
  • 后坐力

我希望我的 NextJS 站点在我单击一个简单按钮时更新每个页面上的值。现在我正在使用 Recoil,因为我发现它是迄今为止最简单的状态管理工具之一。

这是我的_app.js

function MyApp({ Component, pageProps }) {
  return (
    <RecoilRoot>
      < Component {...pageProps} />
    </RecoilRoot>
  )
}

这是index.js

export default function Home() {
  const [city, setCity] = useRecoilState(cityState)
  return (
    <>
      <h1>{city}</h1>
      <button onClick={() => setCity("paris")}>click</button>
    </>
   );
}

这是第 2 页

export default function SecondPage() {
  const [city, setCity] = useRecoilState(cityState)
  return (
    <>
      <h1>{city}</h1>
    </>
   );
}

./state/state.js

export const cityState = atom({
    key: "cityState",
    default: "moscow"
})

当我单击index.js 上的更改按钮时,我只是希望它更改SecondPage 以及我引用存储在state.js 中的状态的所有页面。现在它在index.js 上发生变化,但SecondPage 保持为“莫斯科”。我希望它在单击索引上的按钮时更新。

【问题讨论】:

    标签: javascript reactjs redux next.js state


    【解决方案1】:

    我不知道您的代码结构如何,但我认为您最简单的选择是 React Context API。让我们给你一个更好的解释的例子;

    您的上下文脚本:

     import React, { createContext, useState } from "react";
    
    export const GlobalContext = createContext(); // you can set a default value inside createContext if you want
    
    
    export default function ContextProvider({ children }) {
      const [city, setCity] = useState("moscow")
    
      return (
        <GlobalContext.Provider
          value={[city, setCity]}>
          {children}
        </GlobalContext.Provider>
      );
    }
    

    您的_app.js 文件:

    import ContextProvider from "your_directory"
    
    function MyApp({ Component, pageProps }) {
      return (
        <ContextProvider>
          < Component {...pageProps} />
        </ContextProvider>
      )
    }
    

    index.js文件:

        import ContextProvider, {GlobalContext} from 'your directory'
    
    export default function Home() {
      const [city, setCity] = useContext(GlobalContext)
      return (
        <>
          <h1>{city}</h1>
          <button onClick={() => setCity("paris")}>click</button>
        </>
       );
    }
    

    您的第 2 页脚本:

    import ContextProvider, {GlobalContext} from 'your directory'
    
    export default function SecondPage() {
      const [city] = useContext(GlobalContext)
    
      return (
        <>
          <h1>{city}</h1>
        </>
       );
    }
    

    【讨论】:

    • 如果是本地数据,将提供者包裹在 _app.js 周围就可以了。但是,如果需要从外部获取数据,我们不能在 _app.js 中运行 getserversideprops 或 getstaticprops 不是吗?
    猜你喜欢
    • 2021-09-29
    • 2019-11-28
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 2020-11-26
    相关资源
    最近更新 更多