NextJS,在 getServerSideProps 中预加载 Redux 数据

IT技术 reactjs react-redux next.js
2021-04-15 06:10:08

基于来自 NextJS 官方文档的这些信息,他们建议使用 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,我想看看是否可以通过这种方式完成某些事情。

1个回答

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

总之,既getServerSidedPropsgetInitialProps你需要在服务器端店内传递给到客户是初始客户商店。您可能需要考虑使用next-redux-wrapper来完成此任务。你可以在这里找到一个很好的例子

此外,您缺少react-redux's connecttomapStateToProps和 的用法mapDispatchToProps

我正在使用next.jsreact-redux你类似的配置,我正在努力处理获取存储数据和调度操作所需的所有样板代码。所以我创建了connect-initial-props来让用户更容易地getInitialProps从 redux 存储中分派动作和使用状态数据。欢迎您使用connect-initial-props Github上的示例