Is there a convention for Flux messages sent via the Dispatcher?

只愿长相守 提交于 2019-12-25 10:19:42

问题


I'm building my first React front end and see a number of conventions for messages sent via the Dispatcher. e.g.

{
  type: ActionTypes.RECEIVE_RAW_MESSAGES,
  rawMessages: rawMessages
}

https://github.com/facebook/flux/blob/master/examples/flux-chat/js/actions/ChatServerActionCreators.js#L21

and

{
  source: 'VIEW_ACTION',
  action: action
}

http://facebook.github.io/react/blog/2014/09/24/testing-flux-applications.html#putting-it-all-together

What is the best message format to use & why?


回答1:


The short answer is, it probably doesn't really matter—as long as your stores look for the right data. I always use the following format:

{
  type: 'ACTION_TYPE', // usually defined by a constant
  payload: { ... } // a payload of JSON serializable types
}

If your app needs to distinguish between actions that are initiated by the user and actions that come from the server or some other source, you may considering adding a source key; I personally use separate action types or data within the payload for this purpose.

I always make payload an object (never a raw value) so that data can be added easily without changing receiving sites. For example, instead of

dispatch({type: ACTION_TYPE, payload: id})

I would recommend

dispatch({type: ACTION_TYPE, payload: {id: id}})

Of course, some of this may be dictated by which flux implementation (if any) that you use. The Facebook dispatcher is very agnostic (you can send pretty much anything you want), but some implementations require specific keys (like type, etc).




回答2:


Flux Standard Action is a project to standardize Flux actions.

In short, an action must have a type, and may have a error, payload, or meta.

Examples

{
  type: 'ADD_TODO',
  payload: {
    text: 'Do something.'  
  }
}

For an error:

{
  type: 'ADD_TODO',
  payload: new Error(),
  error: true
}

The meta field is indented for "any extra information that is not part of the payload". I haven't seen this used, so I'd try to stick to payload.



来源:https://stackoverflow.com/questions/29632192/is-there-a-convention-for-flux-messages-sent-via-the-dispatcher

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!