React Js Redux: Action

As last note we had said the core of Redux are Action, Store, Reducer

So that’s try to memories what’s those 3  relation between

For example you need to add a click event, the process is follow:

1 in reducers file add file button.js and write an event constant :

const click => (state, action) { switch (action.type) { case 'ADD' : return state + 1; case 'REMOVE' : return state - 1; } }

2 in action file add file button.js add a function like click(), this method is send the const and data to reducer

3 in container file import action function and send to Button component event

4 Button component will send to DOM

So this simple button event need to get through 4 folder, sounds really complicated right?

Again please look at this picture:

I will advice to look through again the diagram and draw yourself before continuer

Action

Action is the object of Javascript:

const ADD_TODO = 'ADD_TODO'
{
  type: ADD_TODO,
  text: 'Build my first Redux app'
}

Action must have type attribute, it’s present what type of operation (action), type should be defined as string

repeat:

An action MUST

be a plain JavaScript object.
have a type property.

An action MAY

have an error property.
have a payload property.
have a meta property.

you could see more definition flux from here

how action work:

For example if we need to check todo list has done then be checked, we could use index point to specific todo:

{
  type: TOGGLE_TODO,
  index: 5
}

and we need to filter all todo list and show only the completed list:

{
  type: SET_VISIBILITY_FILTER,
  filter: SHOW_COMPLETED
}

You could add as much actin type object you want, but try to keep more simple

Action Creator

Action creator == the function which create action, in Redux action creator return one action, this propose to make code more easy to test and portability:

function addTodo(text) {
  return {
    type: ADD_TODO,
    text
  }
}

In redux you could use dispatch to active the action creator:

dispatch(addTodo(text))
dispatch(completeTodo(index))

follow is the sample code:

/*
 * action type
 */

export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
export const SET_VISIBILITY_FILTER = 'SET_VISIBILITY_FILTER'

/*
 * 其他常數
 */

export const VisibilityFilters = {
  SHOW_ALL: 'SHOW_ALL',
  SHOW_COMPLETED: 'SHOW_COMPLETED',
  SHOW_ACTIVE: 'SHOW_ACTIVE'
}

/*
 * action creator
 */

export function addTodo(text) {
  return { type: ADD_TODO, text }
}

export function toggleTodo(index) {
  return { type: TOGGLE_TODO, index }
}

export function setVisibilityFilter(filter) {
  return { type: SET_VISIBILITY_FILTER, filter }
}

It’s must still confused, if you like to dig more I found this article is great to know the concept

Next :reducer, which  is to change the state