【问题标题】:NextJS, preload Redux data in getServerSidePropsNextJS,在 getServerSideProps 中预加载 Redux 数据
【发布时间】:2020-07-31 12:17:45
【问题描述】:

基于 NextJS 官方文档中的 info,他们建议使用 getServerSidedProps 和 getStaticProps 而不是 getInitialProps。

我想在服务器上预加载一些数据到 Redux 状态。

注意:我使用@redux/toolkit 包

所以我有基本的商店设置:

import reducer from './reducer' // this is just a combineReducers ...
export const store = configureStore({ reducer });

我的自定义 _app.js

import { store } from '../store'

<Provider store={store}>
    <Component {...pageProps} />
</Provider>

现在这是我面临的问题

在 index.js 文件中我有这样的东西

import { store } from '../store'
...
export const getServerSideProps = async (ctx) => {
    const data = await fetchSomeData();
    // here I add some data to the store
    store.dispatch(someAction(data));
    return { props: {} }     
}

数据是在服务器端的存储中设置的,但是当我在客户端时,存储是空的。有谁知道如何在服务器上预加载数据?我不想使用 componentDidMount 的 useEffect 并在客户端上设置该数据。我知道有一个库正在解决这个问题,但它正在使用 getInitialProps 代替,我想看看是否可以通过这种方式完成。

【问题讨论】:

    标签: reactjs react-redux next.js


    【解决方案1】:

    getServerSidedProps 如果您仅在服务器端渲染时需要数据,则应使用该数据。但是,如果您在用户从该页面(您在服务器上获取数据的地方)开始以及客户端导航到该页面时都需要数据,那么最好使用getInitialProps 来获取数据(通过redux-toolkitcreateAsyncThunk)。

    无论如何,对于getServerSidedPropsgetInitialProps,您需要将服务器端存储传递给客户端作为初始客户端存储。您可能要考虑使用 next-redux-wrapper 来完成此任务。你可以找到一个不错的example here

    此外,您缺少使用 react-reduxconnectmapStateToPropsmapDispatchToProps

    我使用的 next.jsreact-redux 与您的配置相似,我正在努力处理获取存储数据和调度操作所需的所有样板代码。所以我创建了connect-initial-props 以使用户getInitialProps 更容易调度操作并使用来自redux 存储的状态数据。欢迎大家参考connect-initial-propsGithub 上的例子。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2020-10-30
      • 2021-09-04
      • 2020-11-01
      • 2020-07-25
      • 1970-01-01
      • 2021-07-15
      • 2021-05-13
      • 2022-05-05
      相关资源
      最近更新 更多