dart - 为什么在比较类时关键字“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
,而是代码继续执行并且函数没有按预期返回。
解决方案
就在我的脑海中,所以不要太相信,但你的问题可能在于参数的“动态”类型导致 is 运算符在编译时失败。我认为可以使用以下方法解决:
DictionaryState dictionaryReducer(DictionaryState state, dynamic action){
if(action.runtimeType == RequestingDictionaryEntryAction){
return _requestingDictionaryEntry(state);
}
if(action.runtimeType == ReceivedDictionaryEntryAction){
return _receivedDictionaryEntry(state, action);
}
return state;
}
推荐阅读
- python - 如何使用 BeautifulSoup 发送密钥
- javascript - JSP 和 Javascript 取消按钮不起作用
- java - 获取不可修改的 MultiKeyMap
- mysql - 我无法使用内部 IP 从另一个实例连接到在 Google Compute 引擎上运行的 mysql 服务器
- javascript - 在数组(JS)中查找第一个唯一的非字谜字符串
- r - 分组后在 dplyr 中使用 t.test 汇总
- c++ - Arduino 上的延迟功能不符合预期
- image - 图像上的水印 - 第 41 行上的 intervention/image/src/Intervention/Image/Commands/Argument.php
- mat-tab - Tinymce编辑器库文件在Angular 5中不活动时不加载。
- android - Android:使用片段在第一个活动中传递参数创建不同的网络