将数据放入 Redux 操作中的 "payload" 键有什么好处?

What are the advantages of putting data inside a "payload" key in a Redux action?

我在任何地方都找不到很好的答案,这似乎是一个毫无意义的约定。在很多教程和文档中,Redux 操作是这样定义的:

{
  type: "ACTION_NAME",
  payload: {
    foo: 123,
    bar: 456,
  }
}

payload 对象有什么意义?为什么不写这个:

{
  type: "ACTION_NAME",
  foo: 123,
  bar: 456,
}

我正在使用 Flow,我喜欢将我所有的操作类型定义为一个联合体,没有嵌套的有效负载:

type Action = {
  type: 'ACTION_NAME',
  foo: number,
  bar: number,
} | {
  type: 'ANOTHER_ACTION',
  someData: string,
} | {
  type: 'ONE_MORE_ACTION',      
  moreData: boolean,
}

我不必多次键入 payload,而且我的所有操作都会自动完成并进行类型检查,所以我不确定我遗漏了什么。

我是否因为没有将所有数据放入 payload 对象而错过了一些好处?

此约定被称为 Flux 标准操作,其动机由 Andrew Clark 阐述为

It's much easier to work with Flux actions if we can make certain assumptions about their shape. For example, essentially all Flux actions have an identifier field, such as type, actionType, or actionId. Many Flux implementations also include a way for actions to indicate success or failure, especially as the result of a data-fetching operation. Defining a minimal, common standard for these patterns enables the creation of useful tools and abstractions.

他对 FSA 的完整建议值得一读。

https://github.com/acdlite/flux-standard-action

简而言之,它使编写中间件(例如 Sagas)变得更容易,并且还可以帮助 Reducers 处理错误状态。