基础使用
Action
- action是一个plain-object(平面对象)
- 它的__proto__指向Object.prototype
- 通常,使用payload属性表示附加数据(没有强制要求)
- action中必须有type属性,该属性用于描述操作的类型
- 但是,没有对type的类型做出要求
- 在大型项目,由于操作类型非常多,为了避免硬编码(hard code),会将action的类型存放到一个或一些单独的文件中(样板代码)。
- 为了方面传递action,通常会使用action创建函数(action creator)来创建action
- action创建函数应为无副作用的纯函数
- 不能以任何形式改动参数
- 不可以有异步
- 不可以对外部环境中的数据造成影响
- 为了方便利用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";
export function getIncreaseAction(){ return { type:actionTYpes.INCRESE, } }
export function getDecreaseAction(){ return{ type:actionTYpes.DECREASE, } }
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";
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());
boundActions.getDecreaseAction()
console.log(store.getState());
boundActions.getIncreaseAction();
console.log(store.getState());
boundActions.getSetAction(3);
console.log(store.getState());
|
Store
Store:用于保存数据
通过createStore方法创建的对象。
该对象的成员:
- dispatch:分发一个action
- getState:得到仓库中当前的状态
- replaceReducer:替换掉当前的reducer
- subscribe:注册一个监听器,监听器是一个无参函数,该分发一个action之后,会运行注册的监听器。该函数会返回一个函数,用于取消监听