Where to put business logic in redux? action or store

后端 未结 3 1375
没有蜡笔的小新
没有蜡笔的小新 2021-02-12 20:51

i come from Reflux to Redux. in Reflux your business logic is exist only in store but in Redux its seems different..for exampl

3条回答
  •  日久生厌
    2021-02-12 21:03

    Here's some opinionated answer which goes against redux recommendations.

    TL;DR Neither

    Longer answer: in so called async action invoked from middleware. In redux community it is known as "thunk" or "saga".

    First, some definitions:

    • action: a plain object { type: 'ACTION_TYPE', payload: { data } }
    • action creator: a function that returns action.
    • async action: a function that is called from middleware.
    • async action creator: a function that returns async action
    • middleware: a function which can handle all actions, dispatch other actions and has access to store state.

    So, where do we call the business logic from?

    If you look carefully, you'll notice that we don't need async action and async action creator. We can have a simple action that is handled directly in the middleware.

    In middleware we can have a dedicated handler for each action. This handler behaves like async action but we don't call it so. Let's call it interactor.

    So a new definition:

    interactor: an abstraction of what is essentially async action in redux, but not redux-specific. Interactor fetches data, calls business logic and dispatches result "actions".

    middleware = (...) => {
      // if(action.type == 'HIGH_LEVEL') 
      interactors[action.name]({ dispatch, params: action.payload })
    }
    
    const interactors = {
      async highLevelAction({ dispatch, params }) {
        dispatch({ loading: true });
        const data = await api.getData(params.someId);
        const processed = myPureLogic(data);
        dispatch({ loading: false, data: processed });
      }
    }
    

    How to dispatch it:

    dispatch({ type: 'HIGH_LEVEL', name: 'highLevelAction', { someId: 1 } })
    

提交回复
热议问题