看看这些东西:
使用这些工具和方法,您最终会
使用从减速器导出的通用选择器,
(它们正在从那些 reducer 负责的子状态中解析通用数据)
然后导入到 rootReducer
它们用于创建另一组通用选择器,但从状态的根解析相同的数据。
在此之后,您基本上可以采用两种概念上不同的方式:
当然,您可以在某种程度上将两者结合起来。
但重要的是要弄清楚界限并将所有事物保留在它们所属的地方。
<...>/FooContainer/selectors.js 和你一起
<...>/FooContainer/FooContainer.jsx 组件。
reducers/entities.js
import { INITIAL_STATE } from 'initialState';
export default (state = INITIAL_STATE.entities, action) => {
/* reducer */
};
export const getModelData = (entities, model, keyWindow) => {
/*
get model data from normalized entities store
using model fields and the keyWindow
*/
};
reducers/index.js
// <...>
/* entities, location, contents - are reducers */
import entities, * as fromEntities from './entities';
import location, * as fromLocation from './location';
import contents, * as fromContents from './contents';
// <...>
export const rootReducer = combineReducers({
entities,
location,
contents,
});
const getEntities = state => state.entities;
const getLocation = state => state.location;
const getContents = state => state.contents;
// <...>
// this is a generic selector for getting the data from
// the entities store.
export const getModelData = createSelector(
[getEntities, (state, model, keyWindow) => ({ model, keyWindow })],
fromEntities.getModelData,
);
// ...
FooContainer/selectors.js
import { getModelData } from 'app/reducers';
export const componentData = createSelector(
[getModelData, (state, model, keyWindow, props) => props],
(modelData, props) => { /* do something specific for your component */},
);
FooContainer/FooContainer.jsx:
import { componentData } from './selectors';
import { FooModel } from 'fooFeature/models';
import { someFooAction, loadFooData } from 'fooFeature/actions';
const getKeyWindow = props => {/* return keyWindow */ };
const mapStateToProps = (state, props) => ({
componentData: componentData(state, FooModel, getKeyWindow(props), props),
});
const mapDispatchToProps = {
someFooAction,
loadFooData,
};
@connect(mapStateToProps, mapDispatchToProps)
class FooContainer extends Component {
static propTypes = {
componentData: PropTypes.arrayOf(PropTypes.object),
loadFooData: PropTypes.func.isRequired,
someFooAction: PropTypes.func.isRequired,
}
/* <...> */
}