【问题标题】:getInitialProps doesn't seem to work when using Next.js with next-redux-wrapper将 Next.js 与 next-redux-wrapper 一起使用时,getInitialProps 似乎不起作用
【发布时间】:2020-08-10 17:02:31
【问题描述】:

我正在尝试使用“next-redux-wrapper”HOC 将我的 next.js Web 应用程序与 redux 挂钩。

我能够通过 getInitialProps 函数从服务器获取数据,但是在使用 next-redux-wrapper 包装我的 _app.js 后,getInitialProps 函数似乎不起作用。

我在这里做错了什么以及如何解决?

import React from 'react'
import fetch from 'isomorphic-unfetch'
import { connect } from 'react-redux'
import { getItems } from '../../store/actions/itemAction'

const Index = (props) => {
  console.log(props)

  return ()
}

Index.getInitialProps = async () => {
  let items
  await fetch('http://localhost:5000/item')
    .then(res => res.json())
    .then(data => { items = data })
    .catch(err => console.log(err))

  return { items }
}

const mapStatetoProps = state => ({
  item: state.item,
})

export default connect(mapStatetoProps, null)(Index)

【问题讨论】:

  • 您使用的是 Next.js 版本 9 以上的版本吗?如果不是,那可能是问题之一。您是否在 github 上查看了 README github.com/kirill-konshin/next-redux-wrapper 中的 next-redux-wrapper 示例?
  • @mdln97 是的,我使用的是最新版本的 nextjs,即 9.3.5。我已经检查了您所指的 next-redux-wrapper 的文档,并且与示例完全相同,但似乎示例中的 getInitialProps 似乎也不起作用。我在示例代码中注释掉了整个 getInitialProps 块,但它仍然适用于被注释掉的代码,这意味着 getInitialProps 在示例代码中永远不会起作用。
  • 这也是在 next.js 文档中,他们提到如果您使用 9.3 以上的 next.js,那么您应该使用 getServerSideProps 或 getStaticProps 而不是 getInitialProps
  • @mdln97 我明白了。我想我将不得不通过文档。感谢您的宝贵时间。

标签: javascript reactjs redux next.js next-redux-wrapper


【解决方案1】:

同样的问题也存在于以下由 zeit/next.js 提供的例子中。见https://github.com/zeit/next.js/tree/master/examples/with-redux-wrapper 在这个例子中,函数“getInitialProps”也没有被调用。自述文件中提到的效果,即时间直接在服务器上预渲染,因此是不可见的。

【讨论】:

    猜你喜欢
    • 2021-09-01
    • 2022-10-14
    • 2018-06-04
    • 2020-05-16
    • 2019-02-05
    • 1970-01-01
    • 2017-07-31
    • 1970-01-01
    • 2020-08-11
    相关资源
    最近更新 更多