代码: https://github.com/JanYLee/recruit-app/tree/demo/basic-redux
专注于状态管理
- 用于状态管理, 和react解耦, 其他框架也可以使用
- 单一状态, 单向数据流
- 核心: store, state, action, reducer
主要流程:
- 通过reducer来创建store, 保存所有状态, 记录state, 通过store.getState获取状态
- 需要更改store时, 从组件里派发(dispatch)出一个行为(action), store.dispatch(action);
- action和state由处理函数(reducer)拿到, 生成新的state, store.subscribe监听每次修改, 更新store
初始化store:
import { createStore } from 'redux';// 1 新建store// 通过reducer生成// 根据老的state和action 生成新的statefunction counter (state=0, action) {switch(action.type) {case 'add':return state+1;case 'delete':return state-1;default:return 10;}}// 新建storeconst store = createStore(counter);const init = store.getState();console.log('init :', init); // init : 10
开始派发action和监听(subscribe)store变化:
function listener() {const curStore = store.getState();console.log(`now store is ${curStore}`);}// 监听每次修改storestore.subscribe(listener);// 派发事件 传递actionstore.dispatch({type: 'add'}); // now store is 11store.dispatch({type: 'add'}); // now store is 12store.dispatch({type: 'delete'}); // now store is 11
