Next.js 和 redux。服务器端填充存储不生效

Next.js and redux. Populating store on server side does not take effect

我将 redux 连接到 Next.js 应用程序只是 like in the docs (not sure what mapDispatchToProps 在示例中所做的):

初始化存储方法:

import { createStore, applyMiddleware } from 'redux';
import { createLogger } from 'redux-logger';
import axios from 'axios';
import axiosMiddleware from 'redux-axios-middleware';
import tokenMiddleware from './tokenMiddleware';
import getReducer from './combineReducers';

const logger = createLogger({ collapsed: true, diff: true });
const axiosMw = axiosMiddleware(axios.create(), { successSuffix: '_SUCCESS', errorSuffix: '_FAILURE' });

export default function initStore(logActions) {
  return function init() {
    const middleware = [tokenMiddleware, axiosMw];
    if (logActions) middleware.push(logger);
    return createStore(getReducer(), applyMiddleware(...middleware));
  };
}

我用来连接页面的HOC:

import 'isomorphic-fetch';
import React from 'react';
import withRedux from 'next-redux-wrapper';
import { setUser } from 'lib/publisher/redux/actions/userActions';
import PublisherApp from './PublisherApp';
import initStore from '../redux/initStore';

export default Component => withRedux(initStore(), state => ({ state }))(
  class extends React.Component {
    static async getInitialProps({ store, isServer, req }) {
      const cookies = req ? req.cookies : null;
      if (cookies && cookies.user) {
        store.dispatch(setUser(cookies.user));
      }

      return { isServer };
    }

    render() {
      console.log(this.props.state);
      return (
        <PublisherApp {...this.props}>
          <Component {...this.props} />
        </PublisherApp>
      );
    }
  }
);

我遇到的问题是调度操作

store.dispatch(setUser(cookies.user));

似乎在服务器上工作正常(我已经调试了 reducer,我知道来自 cookie 的这个用户对象确实由 reducer 处理)但是当我这样做时 console.log(this.props.state) 我得到了具有初始状态的 reducer - 没有用户数据.

您缺少 createStore 调用中的第二个参数。试试这个:

export default function initStore(logActions) {
  return function init(initData) {
    const middleware = [tokenMiddleware, axiosMw];
    if (logActions) middleware.push(logger);
    return createStore(getReducer(), initData, applyMiddleware(...middleware));
  };
}

注意添加了 initData 参数及其用法。