English 中文(简体)
Redux - Core Concepts
  • 时间:2024-12-22

Redux - Core Concepts


Previous Page Next Page  

Let us assume our apppcation’s state is described by a plain object called initialState which is as follows −

const initialState = {
   isLoading: false,
   items: [],
   hasError: false
};

Every piece of code in your apppcation cannot change this state. To change the state, you need to dispatch an action.

What is an action?

An action is a plain object that describes the intention to cause change with a type property. It must have a type property which tells what type of action is being performed. The command for action is as follows −

return {
   type:  ITEMS_REQUEST , //action type
   isLoading: true //payload information
}

Actions and states are held together by a function called Reducer. An action is dispatched with an intention to cause change. This change is performed by the reducer. Reducer is the only way to change states in Redux, making it more predictable, centrapsed and debuggable. A reducer function that handles the ‘ITEMS_REQUEST’ action is as follows −

const reducer = (state = initialState, action) => { //es6 arrow function
   switch (action.type) {
      case  ITEMS_REQUEST :
         return Object.assign({}, state, {
            isLoading: action.isLoading
         })
      default:
         return state;
   }
}

Redux has a single store which holds the apppcation state. If you want to sppt your code on the basis of data handpng logic, you should start spptting your reducers instead of stores in Redux.

We will discuss how we can sppt reducers and combine it with store later in this tutorial.

Redux components are as follows −

Data Handpng Logic

 

Advertisements