【问题标题】:How can I fetch data in getInitialProps in server side when using next.js with redux?将 next.js 与 redux 一起使用时,如何在服务器端的 getInitialProps 中获取数据?
【发布时间】:2020-08-11 11:39:05
【问题描述】:

我正在使用 next.js 和 redux 构建一个 Web 应用程序,并尝试在我刷新或通过直接输入 url 地址访问页面时获取数据。

我在 getInitialProps 中放置了一个“getItems”操作,以便在刷新页面时自动触发它,但它永远不会起作用。

如果我在页面刷新后手动单击“getItems”操作按钮,它会从数据库加载数据,所以我猜操作功能可以正常工作。

但是如何在刷新页面时自动获取数据?

import Head from 'next/head'
import Link from 'next/link'
import { connect } from 'react-redux'
import { getItems } from '../../store/actions/itemAction'

const Index = props => {
  return (
    <>
      <Head>
        <title>Item List</title>
      </Head>
      <div>
        <Button onClick={() => props.getItems()}>Get Items!</Button>
      </div>
    </>
  )
}

Index.getInitialProps = async ({ store }) => {
  await store.dispatch(getItems())
  return {}
}

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

const mapDispatchToProps = dispatch => ({
  getItems: () => dispatch(getItems())
})

export default connect(mapStateToProps, mapDispatchToProps)(Index)

【问题讨论】:

    标签: reactjs redux react-redux next.js


    【解决方案1】:

    根据刷新应用程序时挂载的组件,您必须确保在 componentDidMount 中调用了正在获取数据的任何操作。例如,看看下面我调用 componentDidMount 的 App.js:

       class App extends React.Component {
    
          componentDidMount = () => {
            this.props.persistUser()
            this.props.fetchAndSetAllPosts()
            console.log('refreshed')
          }
    }
    

    我从我的操作文件夹“this.props.fetchAndSetAllPosts()”中导入了 fetch 函数,这是一个从 API 获取的操作。因此,每次刷新页面时,组件挂载都应该执行您在 componentDidMount 中调用的任何内容。 console.log() 一条消息,以确保它正确触发。让我知道这是否有帮助!祝你好运!

    【讨论】:

    • 感谢您的友好回答。我刚刚发现在服务器端渲染中获取了数据,并且数据正确地存储在 redux 存储中,但问题是获取的数据在那之后永远不会移动到页面道具。当我检查“store.getState()”时,存储了获取的数据。你知道为什么数据永远不会移动到页面道具吗?
    • 嗯,我唯一的其他建议是在您的代码中查看以下内容:Index.getInitialProps = async ({ store }) => { await store.dispatch(getItems()) return {}它似乎返回了一个空对象,并且您似乎希望它在重新加载时实际返回获取的数据。看看这个链接,看看它是否有帮助:nextjs.org/docs/api-reference/data-fetching/getInitialProps 如果有帮助,请告诉我!
    猜你喜欢
    • 2018-08-31
    • 2019-07-18
    • 2020-08-10
    • 1970-01-01
    • 2020-06-04
    • 2021-11-20
    • 2019-02-05
    • 2022-11-10
    • 2020-08-11
    相关资源
    最近更新 更多