React Redux: Should reducers contain any logic

前端 未结 4 1363
孤城傲影
孤城傲影 2020-12-25 12:25

I have a cart reducer function with add, update and delete cases. I also have a product array within the redux store. When there are two items added to the product array, i

4条回答
  •  时光取名叫无心
    2020-12-25 13:03

    No, they shouldn't contain logic

    Actions gather and emit large objects that reducers split into proper locations

    Instead of large objects, you may procedurally dispatch actions at each step in an action creator, which is what the top answer seems to promote (yet is impossible with plain redux)


    • Components: pass existing redux data into actions
    • Actions: gather data and emit large object, applicable to as many reducers as possible
    • Reducers: extract action object for granular, non-repeating, flat storage (as opposed to monolithic, redundant, nested folders). I recommend explicit initialState for easy maintenance and blatantly obvious data shape (states should never change shape; if joined objects are unavailable, serialize by id rather than sometimes nesting full objects)
    • *Side Effects: subsequent action listener/dispatchers, useful when you don't want to wait before emitting an initial event (sagas are subscription-based, thunks are declarative chains)

    A rule of thumb is to do everything as eagerly as possible

    Eager operation (early return, fail fast, hoisting state, etc) clarifies whether specific dependencies exist concurrently, and makes for easy decisions

    Eager operation falls in line with “separation of concerns” and a simple theme for modular, declarative, stateful, pragmatic, legible code: declare dependencies, operate, and return

    Everything else is a matter of sequencing, which should be done as eagerly as possible

    A reducer is the last place you’d want to be “doing” anything. It’s effectively a “return” and should simply select data from action objects

提交回复
热议问题