【问题标题】:Flow: choosing between actions in the reducer流程:在 reducer 中的操作之间进行选择
【发布时间】: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 语句中抱怨该字段我正在尝试使用的(在本例中为foobar)在第一个操作中不存在。

让Flow开心的正确方法是什么?

【问题讨论】:

    标签: redux flowtype


    【解决方案1】:

    flow 不喜欢这样的原因是因为 ActionWithEntities 的 type 字段是 string 类型,这意味着它的值可能是 FOO 或 BAR。现在,您的逻辑将阻止它触发开关/案例,但流程无法遵循该逻辑并改进类型。解决它的一种方法是显式键入 ActionWithEntities 的类型字段

    类似

    type ActionWithEntities = {|
      type: 'OTHER' | 'OTHER2' | 'OTHER3',
      payload: {|
        entities: {|
          items: {
            [string]: string
          }
        |}
      |}
    |}
    

    【讨论】:

    • 那很不幸。我认为当给定一组明确的 if 语句时,Flow 能够改进类型。不知道Flow有没有办法从字符串类型中排除某组字符串,这样我就不需要在type字段中枚举所有可能的字符串,而是说这个字段是一个既不是FOO 还是 BAR?
    • @azangru:我认为您不能从 string 类型中排除某些字符串。不可能进行静态类型检查。
    猜你喜欢
    • 2014-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-03
    • 2011-12-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-10
    相关资源
    最近更新 更多