【发布时间】:2017-08-25 10:05:37
【问题描述】:
我正在研究使用 Flow 输入 Redux 操作的方法。使用以下定义,它部分地在动作创建者和减速器中工作。自动完成将所有 4 个操作作为action.type 在两个位置的可能值。
// @flow
type ModuleActionTypes1 = 'moduleOne/ACTION_ONE' | 'moduleOne/ACTION_TWO';
type ModuleActionTypes2 = 'moduleTwo/ACTION_ONE' | 'moduleTwo/ACTION_TWO';
type ActionTypes = ModuleActionTypes1 | ModuleActionTypes2;
type Action<T> = {
type: ActionTypes,
payload: T
};
type Payload = {
url: string
};
const actionCreator = (url: string): Action<Payload> => {
return {
type: 'moduleOne/ACTION_ONE',
payload: {
url: url
}
};
};
const reducer = (state: string, action: Action<Payload>): string => {
if(action.type === 'wrong') {
// action.type cannot be this
}
switch (action.type) {
case 'moduleOne/ACTION_ONE':
case 'wrong': // action type cannot be this
const { url } = action.payload;
return url;
default:
return state;
}
};
它几乎可以满足我的要求。主要有两个问题:
switch case 不必是
action.type之一,因此拼写错误可能会漏掉。这表明我应该坚持使用字符串常量。当我
import type { ModuleActionTypes1 } from '../moduleOne';(而不是在同一个文件中定义它进行测试)时,自动完成功能停止工作,但流在命令行上没有报告任何错误。所有文件都包含@flow 注释。
有没有更好的方法来做到这一点?
【问题讨论】:
标签: javascript redux flowtype