简体   繁体   中英

Redux store.dispatch purpose

I'm reviewing a TypeScript function which performs some algorithmic logic and trying to understand where the logic actually happens

private DoSomeAlgorithmicLogic(nodeIds: any) {
  const obj = CreateObject(nodeIds);
  this.store.dispatch(new GetNodes(obj));
  }

CreateObject fills verious attributes of obj and GetNodes is merly this:

export class GetNodes implements Action {
  readonly type = GET_NODES;
  constructor(public payload: any) {
  }
}

I tried reading about store & dispatch here but not sure I understood the concepts presented.

What I really need is pointers as how to further investigate/debug this functionality in order to find where the logic happens, but will be happy to get further explenation regarding app state tree and how this line relates to it (especially the parameter that should be passed to dispatch() ).

Action Creators

It looks like whoever wrote this code got a little bit too excited by OOP and ignored the principles of Redux. An action should be serializable so using a class as an action creator is not a good idea.

dispatch is a function which takes an Action . An Action is an object with a type: string property and possibly some other data. So you can call:

dispatch({type: MY_ACTION});
dispatch({type: MY_ACTION, payload: someData});

But typically we use action creator functions to create the action object. That is what this class GetNodes is doing, but it's a bizarre way to do it. It should probably just be a function:

export const getNodes = (payload: any): Action => ({
  type: GET_NODES,
  payload
})

I hate this payload: any because any really defeats the point of using Typescript. It should probably be something like payload: Node[] .

With the action creator function, you call:

dispatch(getNodes(obj));

Logic

Action creators generally don't have any logic. They just arrange the arguments into an Action object.

Redux logic happens in the reducer. The reducer is a function that takes the current state and the dispatched action and returns the next state.

const myReducer = (state: MyState, action: Action): MyState => {...

The reducer is passed as an argument when you create the store instance. You will either find one reducer function or a function created by calling combineReducers with a map object of reducer functions. Look for where this.store is set and look for the first argument of createStore . That's the reducer function where you will find all of the logic for handling various actions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM