我将 redux 连接到 Next.js 应用程序,就像在文档中一样(但不确定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));
似乎在服务器上工作正常(我已经调试了减速器,我知道这个来自 cookie 的用户对象确实由减速器处理)但是当我这样做时,console.log(this.props.state)
我得到了具有初始状态的减速器 - 没有用户数据。