【发布时间】:2018-06-10 11:22:06
【问题描述】:
TLDR:我已经在 Try Flow (link) 中模拟了我的问题。你能帮我解决一下吗?
问题的完整描述:
在 Redux reducer 中,我在三个操作之间进行选择。一个动作可以有任何类型,但它的独特之处在于它的有效负载中有一个特定的字段(在这个例子中是payload.entities.items)。另外两个动作有特定的类型来区分它们,并且也有不同的负载:
const FOO = 'FOO'
const BAR = 'BAR'
type ActionWithEntities = {|
type: string,
payload: {|
entities: {|
items: {
[string]: string
}
|}
|}
|}
type ActionWithFoo = {|
type: typeof FOO,
payload: {|
foo: string
|}
|}
type ActionWithBar = {|
type: typeof BAR,
payload: {|
bar: string
|}
|}
type Action =
| ActionWithEntities
| ActionWithFoo
| ActionWithBar
根据操作,我想在减速器中做任何适当的事情(并不重要):
function reducer(state: State, action: Action) {
if (action.payload && action.payload.entities && action.payload.entities.items) {
return Object.assign({}, state, action.payload.entities.items);
}
switch(action.type) {
case FOO:
const foo = action.payload.foo;
return { foo }
case BAR: {
const bar = action.payload.bar;
return { bar }
}
default:
return state;
}
}
我的问题是,Flow 没有看到 if 语句处理第一个操作(因为其他操作在其有效负载中没有 entities 字段),并在 switch 语句中抱怨该字段我正在尝试使用的(在本例中为foo 或bar)在第一个操作中不存在。
让Flow开心的正确方法是什么?
【问题讨论】: