【发布时间】:2017-08-30 03:13:29
【问题描述】:
我有一个用于存储首选项的减速器。它有两种动作类型。一个用于从数据库加载所有首选项,另一个用于更新单个首选项。我有一个独立的示例,但是一旦在我的应用程序中使用它就会中断。
问题是我的偏好减速器只处理两种类型的动作,而我的应用程序有多个触发其他动作的减速器。让代码运行的一种解决方案是为与此 reducer 无关的操作添加第三种通用类型。但是,当我尝试访问操作的属性时,这会产生 Property not found in 'object type'. 错误。
// @flow
const LOAD_PREFS_SUCCESS = 'LOAD_PREFS_SUCCESS';
const UPDATE_PREF = 'UPDATE_PREF';
type aType = {
+type: string
};
export type actionType = {
+type: typeof LOAD_PREFS_SUCCESS,
prefs: Array<{_id: string, value: any}>
} | {
+type: typeof UPDATE_PREF,
id: string,
value: any
};
export default (state: {} = {}, action: actionType) => {
if (action.type === LOAD_PREFS_SUCCESS) {
action.prefs.forEach(p => {
console.log(p);
});
}
switch (action.type) {
case LOAD_PREFS_SUCCESS: {
const newState = {};
action.prefs.forEach(p => {
newState[p._id] = p.value;
});
return newState;
}
case UPDATE_PREF: {
return { ...state, [action.id]: action.value };
}
default:
return state;
}
};
这是有效的流程,但是当应用程序实际运行时,当类型为 INIT_APP 的操作或其他内容运行时出现错误。错误显示action must be one of:,然后它列出了我在actionType 中的两种类型作为预期和{ type: string } 的实际类型。
我可以通过向actionType 添加第三种类型来运行应用程序,如下所示:
export type actionType = {
+type: typeof LOAD_PREFS_SUCCESS,
prefs: Array<{_id: string, value: any}>
} | {
+type: typeof UPDATE_PREF,
id: string,
value: any
} | {
+type: string
};
即使应用程序现在运行没有错误,它也没有通过流类型检查。抛出Property not found in object type 的错误。 Here is an example on flow.org
【问题讨论】: