小编Dav*_*lva的帖子

如何使用 redux-saga 获取 getInitialProps 中的数据。然后在 getInitialProps 方法中从 redux 存储中获取响应?

我完成了使用 create-react-app (CSR) 创建的 React 应用程序的编码,但现在我正在使用 Next.js 框架重写整个应用程序,以获得更好的 SEO 性能。

在重写它时,我很难弄清楚如何正确处理 redux 和 redux-saga 来执行获取和存储数据过程。在这个项目中使用 Next.js 的主要原因是利用 getInitialProps 方法,在第一个页面加载发生之前获取服务器端的数据。但由于某种原因,我无法“等待”Redux 调度完成并按时获取获取的数据。

所以最终发生的情况是,我调度了获取数据的操作,但在初始服务器端页面加载期间它没有按时存储在 redux 存储中。但是,当我使用 next/link 更改路由时,数据会进入,但仅在客户端渲染发生后。

所以它有点违背了使用 Next.js 的目的。

这个新代码与 create-react-app 项目非常相似,只是进行了一些细微的更改以适应 Next.js 项目的要求。

这是我的代码。

./pages/_app.js

import App from 'next/app';
import { Provider } from 'react-redux';
import withRedux from 'next-redux-wrapper';
import withReduxSaga from 'next-redux-saga';
import makeStore from '../store/index';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    const pageProps = Component.getInitialProps
      ? await Component.getInitialProps(ctx)
      : {};
    return { …
Run Code Online (Sandbox Code Playgroud)

reactjs redux server-side-rendering redux-saga next.js

6
推荐指数
1
解决办法
6745
查看次数