gpt4 book ai didi

redux - 在 Next.js 中使用 Redux 是一种反模式吗?

转载 作者:行者123 更新时间:2023-12-03 07:30:54 24 4
gpt4 key购买 nike

我正在构建一个 Next.js 应用程序,它目前正在使用 Redux。在我构建它时,我想知道是否真的有必要使用 Redux,它的使用是否实际上是一种反模式。这是我的推理:

为了在 Next.js 中正确初始化 Redux Store,您必须创建一个自定义 App带有 getInitialProps 的组件方法。通过这样做,您将禁用 Automatic Static Optimization Next.js 提供的。

相比之下,如果我要在客户端包含 Redux,则只有在 App 挂载后,Redux 商店才会在每次服务器端导航后重置。例如,我有一个 Next.js 应用程序,它在客户端初始化 Redux 存储,但是当路由到动态路由时,例如 pages/projects/[id] ,页面是服务器端呈现的,我必须重新获取商店中的任何信息。

我的问题是:

  • 在这种情况下,Redux 商店有什么好处?
  • 我应该在根目录中初始化存储 App组件并放弃自动静态优化?
  • 有没有更好的方法来管理 Next.js 9.3 中的状态 getStaticPropsother data fetching methods
  • 我错过了什么吗?
  • 最佳答案

    If you have a custom App with getInitialProps then the AutomaticStatic Optimization that Next.js provides will be disabled for allpages.


    没错,如果您遵循这种方法。

    Is there a better way ?


    是的,您可以创建一个 Redux Provider 作为包装器并包装您需要的组件,redux 上下文将自动初始化并在该组件中提供。
    例子:
    const IndexPage = () => {
    // Implementation
    const dispatch = useDispatch()
    // ...
    // ...
    return <Something />;
    }

    IndexPage.getInitialProps = ({ reduxStore }) => {
    // Implementation
    const { dispatch } = reduxStore;
    // ...
    // ...
    }

    export default withRedux(IndexPage)
    您现在可以仅将 Redux 用于需要状态管理的页面,而无需禁用整个应用程序的优化。
    回答你的问题“在 Next.js 中使用 Redux 是一种反模式吗?”
    不会,但需要正确使用。
    有关如何在此处完成的更多信息: https://github.com/vercel/next.js/tree/canary/examples/with-redux
    我希望这有帮助

    关于redux - 在 Next.js 中使用 Redux 是一种反模式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60626451/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com