我已经接受了上面 James J. 的答案,因为他花时间给出了一个完全有效的答案,我认为他是一个很好的解决方案。不过,我认为我应该包括我最终使用的解决方案。没有一个正确的答案,但我不喜欢将任何业务逻辑放在视图层中的想法(感觉它不应该在那里,redux 提供了其他选择)。
首先,这是一个无聊的顶级连接组件。唯一需要注意的是通过operators 公开的initializeApplication() 方法属性和ready 状态属性(可通过来自redux 的state.application 获得。
// components/Application.js
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { operators, selectors } from './store'; // eslint-disable-line no-unused-vars
class Application extends React.Component {
componentDidMount() {
this.props.initializeApplication();
}
render() {
return <div>Application ready? { this.props.application.ready }</div>;
}
}
const mapStateToProps = state => ({
application: state.application,
});
const mapDispatchToProps = ({
initializeApplication: operators.initializeApplication,
});
export default connect(mapStateToProps, mapDispatchToProps)(Application);
这是应用程序的 redux 部分。它使用a variation of the ducks 结构。在ducks中,所有的动作都是通过“操作符”暴露出来的(基本上,类型被动作包裹,动作被动作创建者包裹,被操作符包裹)。
// store/Application/index.js
import { createReducer } from '../../Utils';
import { operators as UserPrefs } from '../UserPrefs';
import { operators as Api } from '../Api';
// TYPES:
const types = {
INITIALIZED: 'Application/initialized'
};
// ACTION CREATORS:
const actions = {
initialized: () => ({ type: INITIALIZED })
};
// OPERATORS:
const initializeApplication = () => dispatch =>
Promise.all([
dispatch(UserPrefs.initializeUserPrefs()),
dispatch(Api.initializeApi())
])
.then(() => dispatch(actions.initialized()));
const operators = {
initializeApplication
};
// REDUCER:
const initialShape = {
ready: false
};
const reducer = createReducer(initialShape)({
[INITIALIZED]: (state) => ({...state, ready: true })
});
// EXPORTS
export default reducer;
export {
operators,
types
};
显然,这里调用的操作符必须返回只有在它们完成运行后才会解析的承诺。例如:
// store/UserPrefs/index.js
// ** NOT INCLUDING REDUCERS, TYPES, ETC **
const initializeUserPrefs = () => dispatch =>
Promise.all([
loadDefaultPrefs(),
loadCurrentPrefs()
])
.then(
([
defaultPrefs,
currentPrefs
]) => dispatch(actions.initialized(defaultPrefs, currentPrefs))
);
const operators = {
initializeInventory
};
export {
operators
};
这里唯一有争议的是,这些鸭子式减速器模块中的一些必须“了解”其他鸭子(application 知道userPrefs 和api)并直接调度其操作符,引入紧密绑定,但由于 redux 允许分层化简树,我不认为这会破坏游戏规则,但我明白为什么有些人也不喜欢这个解决方案。