redux action

Action

Action is the payload that transfers data from the application to the store. It is the only source of store data. Generally, you will pass the action to the store via store.dispatch().
The action to add a new todo task is like this:

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

Action is essentially a normal JavaScript object. We agree that a string type field must be used in the action to indicate the action to be performed.

In most cases, type will be defined as a string constant. When the application scale becomes larger and larger, it is recommended to use a separate module or file to store the action.

import {
    
     ADD_TODO, REMOVE_TODO } from '../actionTypes'

Action creation function

Action creation function is the way to generate action.
The action creation function in Redux simply returns an action:

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

In Redux, you only need to pass the result of the action creation function to the dispatch() method to initiate a dispatch process.

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

Or create a bound action creation function to automatically dispatch:

const boundAddTodo = text => dispatch(addTodo(text))
const boundCompleteTodo = index => dispatch(completeTodo(index))

Then call them directly:

boundAddTodo(text);
boundCompleteTodo(index);

Source code

/*
 * action 类型
 */

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 创建函数
 */

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 }
}

Now let us develop some reducers to illustrate how the state should be updated after the action is initiated.

Guess you like

Origin blog.csdn.net/qq_45429539/article/details/114300295