【发布时间】: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