## redux的工作流程
使用函数createStore创建store数据点
1 2 3 4 5 6 7 8 9 import { createStore } from 'redux' ;import reducer from './reducer' const store = createStore( reducer, window .__REDUX_DEVTOOLS_EXTENSION__ && window .__REDUX_DEVTOOLS_EXTENSION__() ); export default store;
创建Reducer。它要改变的组件,它获取state和action,生成新的state
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 import { CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM } from './actionTpyes' const defaultState = { inputValue:'' , list: [] } export default (state = defaultState,action) => { if (action.type === CHANGE_INPUT_VALUE) { const newState = JSON .parse(JSON .stringify(state)); newState.inputValue = action.value; return newState } if (action.type === ADD_TODO_ITEM) { const newState = JSON .parse(JSON .stringify(state)); newState.list.push(newState.inputValue); newState.inputValue = '' return newState } if (action.type === DELETE_TODO_ITEM) { const newState = JSON .parse(JSON .stringify(state)); newState.list.splice(action.index,1 ) return newState } return state; }
用subscribe监听每次修改情况
1 2 3 4 constructor (props) { super (props); store.subscribe(this .handleStoreChange) }
dispatch执行,reducer(currentState,action)处理当前dispatch后的传入的action.type并返回给currentState处理后的state,通过currentListeners.forEach(v=>v())执行监听函数,并最后返回当前 action状态
1 2 3 4 5 6 7 handleItemDelete(index) { const action = { type: DELETE_TODO_ITEM, index } store.dispatch(action) }
subscribe的作用 subscribe 这个函数是用来去订阅 store 的变化,比如你每次对 store 进行 dispatch(action) 都会触发 subscribe 注册的函数调用,这个在实际情况不是必须要的,看自己的应用场景,比如你想监控 store 的全局变化时 可以用 subscript 订阅一下,然后作一些反应
每次通过dispatch 修改数据的时候,其实只是数据发生了变化,如果不手动调用 render方法,页面上的内容是不会发生变化的。
但是每次dispatch之后都手动调用很麻烦啊,所以就使用了发布订阅模式,监听数据变化来自动渲染。