You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NgRx:如何在选择器内延迟评估另一个选择器

解决方案

核心思路

通过提取Foo的创建逻辑为独立函数,在目标选择器中先判断状态有效性,仅当状态有效时才执行Foo的创建与isBar()判断,同时保留原有选择器的接口,无需修改调用代码。

具体实现

  1. 抽离Foo创建逻辑
    把原fooSelector中的Foo构造逻辑单独提取,保证逻辑复用且一致性:
// 抽离Foo创建逻辑,状态无效时抛出错误(与原逻辑一致)
const createFoo = (input1: Input1, input2: Input2, input3: Input3): Foo => {
  // 原fooSelector中的合并逻辑示例
  if (!input1 || !input2 || !input3) {
    throw new Error("状态无效,无法生成Foo实例");
  }
  return { /* 构造Foo实例的具体逻辑 */ };
};
  1. 保留原fooSelector
    原选择器保持不变,避免影响其他依赖它的代码:
export const fooSelector = createSelector(
  inputSelector1,
  inputSelector2,
  inputSelector3,
  createFoo
);
  1. 重构目标选择器
    修改isValidStateAndFooIsBarSelector,先判断状态有效性,仅在有效时才创建Foo并执行判断:
export const isValidStateAndFooIsBarSelector = createSelector(
  isValidSelector,
  inputSelector1,
  inputSelector2,
  inputSelector3,
  (isValid: boolean, input1: Input1, input2: Input2, input3: Input3): boolean => {
    // 状态无效直接返回false
    if (!isValid) return false;
    
    try {
      // 状态有效时安全创建Foo并判断isBar
      const foo = createFoo(input1, input2, input3);
      return foo.isBar();
    } catch (err) {
      // 额外容错:防止isValid判断不严谨导致的异常
      return false;
    }
  }
);

测试兼容性

该选择器仍可通过NgRx官方测试工具(如@ngrx/store/testing)进行验证:

  • 模拟isValid: false的状态,验证返回false
  • 模拟isValid: true且输入合法的状态,验证返回foo.isBar()的结果
  • 模拟isValid: true但输入非法的状态,验证返回false(通过catch块处理)

内容的提问来源于stack exchange,提问作者MageWind

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 12:07:16