首页 > 解决方案 > 为什么在比较类时关键字“is”没有按预期运行?

问题描述

我在我的飞镖应用程序中使用了一个 redux 模式。在 reducer 内部,具有"is"关键字来确定正在传递哪个操作(以类的形式)的 if 语句根本不起作用。

DictionaryState dictionaryReducer(DictionaryState state, dynamic action){

  if(action is RequestingDictionaryEntryAction){
    // This if statement should be executed but it is not.
    return _requestingDictionaryEntry(state);
  }

  if(action is ReceivedDictionaryEntryAction){
    return _receivedDictionaryEntry(state, action);
  }

  return state;
}

调用dictionaryReducer时,我传递了一个被调用的动作RequestingDictionaryEntryAction,但它没有被识别为RequestingDictionaryEntryAction,而是代码继续执行并且函数没有按预期返回。

标签: dart

解决方案


就在我的脑海中,所以不要太相信,但你的问题可能在于参数的“动态”类型导致 is 运算符在编译时失败。我认为可以使用以下方法解决:

DictionaryState dictionaryReducer(DictionaryState state, dynamic action){

  if(action.runtimeType == RequestingDictionaryEntryAction){
    return _requestingDictionaryEntry(state);
  }

  if(action.runtimeType == ReceivedDictionaryEntryAction){
    return _receivedDictionaryEntry(state, action);
  }

  return state;
}

推荐阅读