我设法为选择器提供了参数,并稍微改变了我的使用方式。示例:
选择器(这里我不使用单独的功能)
export const selectReferentialsState = (state: AppState) => state.referentials;
export const referentialDataSelector = createSelector(
selectReferentialsState,
(state: ReferentialsState, props: { refType: Referential}) => state.data[props.refType]
);
用法
this.availableRoles$ = this.store.select(state => referentialDataSelector(state, { refType: Referential.Role}));
高级用法(带参数的级联选择器)
我将提供另一个示例来涵盖更复杂的场景,即必须定义一个依赖于需要参数的选择器 (props) 的选择器。这还包括更简单的使用语法(pipe + select):
export const selectQuestionnaireTranslationInfo = createSelector(
selectQuestionnaireTranslationState,
(state: QuestionnaireTranslationState, props: { formId: number}) => state.entities[props.formId]
);
export const selectQuestionnaireLanguageProgress = createSelector(
selectQuestionnaireTranslationInfo,
(state: QuestionnaireTemplateTranslationFullInfo, props: {formId: number, langId: number }) =>
state?.languageInfo?.find(li => li.spTranslationLanguageId === props.langId)
);
export const selectQuestionnaireLanguageProgressCount = createSelector(
selectQuestionnaireLanguageProgress,
(state: QuestionnaireTemplateTranslationLanguageInfo) =>
state?.translatedResourceCount
);
用法:
const props = { formId: this.templateId, langId: this.languageId};
this.progressCount$ = this.store.pipe(select(selectQuestionnaireLanguageProgressCount, props));`
正如Ian Jamieson 已经指出的那样,props 被合并并在选择器链中可用(这就是为什么最后一个选择器不需要显式声明 props,它们是“继承的”)。