Redux: Why not put actions and reducer in same file?

前端 未结 2 1852
梦谈多话
梦谈多话 2020-12-13 19:18

I\'m creating an app with Redux and am scratching my head as to why it is best to place actions and reducers in separate files. At least, that\'s the impression I\'m getting

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 20:12

    From Redux creator Dan Abramov:

    Many reducers may handle one action. One reducer may handle many actions. Putting them together negates many benefits of how Flux and Redux application scale. This leads to code bloat and unnecessary coupling. You lose the flexibility of reacting to the same action from different places, and your action creators start to act like “setters”, coupled to a specific state shape, thus coupling the components to it as well.

    From the Redux docs:

    We suggest you write independent small reducer functions that are each responsible for updates to a specific slice of state. We call this pattern “reducer composition”. A given action could be handled by all, some, or none of them. This keep components decoupled from the actual data changes, as one action may affect different parts of the state tree, and there is no need for the component to be aware of this.

    See this conversation on twitter and this issue on github for more information.

提交回复
热议问题