reactjs - NextJS,在 getServerSideProps 中预加载 Redux 数据

标签 reactjs react-redux next.js

基于此info从官方 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 ,我想看看是否可以通过这种方式完成某些事情。

最佳答案

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

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

此外,您缺少 react-redux 的用法的connectmapStateToPropsmapDispatchToProps .

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

关于reactjs - NextJS,在 getServerSideProps 中预加载 Redux 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61281070/

相关文章:

javascript - 使用 React 组件分发 CSS

javascript - 在元素内 react 转义变量

javascript - 这个 Flow JS "polymorphic type instead of intersection type"错误是什么意思?

jquery - 将 Owl Carousel 2 与 next.js 一起使用并使用react

javascript - Redux - 如果状态属性为空(Typeerror)

reactjs - 当我点击 yarn run dev 。它显示 'next' 不是内部或外部命令,也不是可运行的程序或批处理文件

javascript - 如何自动聚焦于 React 中的特定输入字段(单击另一个元素后)?

reactjs - 在 React 中从另一个文件导出函数时出现问题

android - 未定义不是 React Native 项目中的函数

reactjs - Redux Form - 初始值不随状态更新