redux redux的基础使用

基础使用

Action

  1. action是一个plain-object(平面对象)
    1. 它的__proto__指向Object.prototype
  2. 通常,使用payload属性表示附加数据(没有强制要求)
  3. action中必须有type属性,该属性用于描述操作的类型
    1. 但是,没有对type的类型做出要求
  4. 在大型项目,由于操作类型非常多,为了避免硬编码(hard code),会将action的类型存放到一个或一些单独的文件中(样板代码)。
  5. 为了方面传递action,通常会使用action创建函数(action creator)来创建action
    1. action创建函数应为无副作用的纯函数
      1. 不能以任何形式改动参数
      2. 不可以有异步
      3. 不可以对外部环境中的数据造成影响
  6. 为了方便利用action创建函数来分发(触发)action,redux提供了一个函数bindActionCreators,该函数用于增强action创建函数的功能,使它不仅可以创建action,并且创建后会自动完成分发。

actionTypes.js

1
2
3
export const INCRESE = Symbol("increse");
export const DECREASE = Symbol("descrease");
export const SET = Symbol("set");

actionCreate.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import * as actionTYpes from "./actionTypes";

/**
* increase action的创建函数
* @returns {{type: symbol}}
*/
export function getIncreaseAction(){
return {
type:actionTYpes.INCRESE,
}
}

/**
* decrease action的创建函数
* @returns {{type: *}}
*/
export function getDecreaseAction(){
return{
type:actionTYpes.DECREASE,
}
}

/**
* set action 的创建函数
* @param newNumber
* @returns {{payload, type: *}}
*/
export function getSetAction(newNumber){
return{
type:actionTYpes.SET,
payload:newNumber
}
}

index.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import {createStore,bindActionCreators} from "redux";
import * as createActions from "./actionCreate";
import * as actionTypes from "./actionTypes";

/**
* reducer本质上就是一个普通的函数
* @param state 之前仓库中的数据
* @param action 描述要做什么的对象
*/
function reducer(state,action){
// 返回一个新的状态
if(action.type === actionTypes.INCRESE){
return state + 1;
}else if (action.type === actionTypes.DECREASE){
return state - 1;
}else if(action.type === actionTypes.SET){
return action.payload;
} else{
return state;
}
}

const store = createStore(reducer,10);
const boundActions = bindActionCreators(createActions,store.dispatch);
console.log(store.getState()); //10

boundActions.getDecreaseAction()

console.log(store.getState());//9

boundActions.getIncreaseAction();

console.log(store.getState());//10

boundActions.getSetAction(3);

console.log(store.getState());//3

Store

Store:用于保存数据

通过createStore方法创建的对象。

该对象的成员:

  • dispatch:分发一个action
  • getState:得到仓库中当前的状态
  • replaceReducer:替换掉当前的reducer
  • subscribe:注册一个监听器,监听器是一个无参函数,该分发一个action之后,会运行注册的监听器。该函数会返回一个函数,用于取消监听