简体   繁体   English

使用 Next.js 在两个页面之间持久化数据

[英]Persist data between two pages with Next.js

I would like to refactor my Next.js webapp to have different pages handle different screens.我想重构我的 Next.js webapp 让不同的页面处理不同的屏幕。 Currently, I have this component holding several states to know in which screen I'm in. In the jsx section, I'm using {value &&... } to render the right component.目前,我有这个组件持有几个状态来知道我在哪个屏幕中。在 jsx 部分,我使用{value &&... }来呈现正确的组件。

But I feel this is not good design, and won't be maintainable when adding more and more screens.但是我觉得这不是很好的设计,当屏幕越来越多时将无法维护。

I would also like to avoid Redux as it is overkill for my project.我也想避免 Redux 因为它对我的项目来说太过分了。

I was thinking about persisting data in cookies so I can retrieve them with getInitialProps in every component when rendering a new page, but is there a more elegant way?我正在考虑在 cookies 中保留数据,以便在呈现新页面时可以在每个组件中使用 getInitialProps 检索它们,但是有没有更优雅的方法?

I've read about tweaking the _app.js but I'm not sure to understand the consequences of doing so, and how it could help me..我已经阅读了有关调整_app.js的信息,但我不确定这样做的后果,以及它如何帮助我..

Any suggestion?有什么建议吗?

When multiple of your pages need to make use of same data, you can make use of Context to store the result.当您的多个页面需要使用相同的数据时,您可以使用 Context 来存储结果。 It a good way to make a centralized storage without using complex and more self sufficient libraries like redux这是一种无需使用复杂且更自给自足的库(如redux即可进行集中存储的好方法

You can implement context inside of _app.js file which must reside inside your root folder.您可以在 _app.js 文件中实现上下文,该文件必须位于根文件夹中。 This way next.js treats it as a root wrapper and you would just need to use 1 instance of Context这样 next.js 将其视为根包装器,您只需要使用 1 个 Context 实例

contexts/appContext上下文/appContext

import React from 'react';
const AppContext = React.createContext();
export const AppProvider = AppContext.Provider;
export const AppConsumer = AppContext.Consumer;
export default AppContext;

_app.js _app.js

import React from 'react'
import App from 'next/app'
import AppProvider from '../contexts/appContext';
class MyApp extends App {
  state={
    data:[]
  }
  render() {
    const { Component, pageProps } = this.props;
    // You can implement logic in this component to fetch data and update state
    return (
      <div>
        <AppProvider value={this.state.data}> // pass on value to context
          <Component {...pageProps} />
        </AppProvider>
      </div>
    )
  }
}
export default MyApp

Now further each component can make use of context value by using AppConsumer or using useContext if you use hooks现在进一步每个组件可以通过使用 AppConsumer 或useContext如果你使用钩子来使用上下文值

Please read more about how to use Context here在此处阅读有关如何使用上下文的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM