一筷弦、Redux的過程
1.使用函數(shù) createStore 創(chuàng)建 store 數(shù)據(jù)點(diǎn)
2.創(chuàng)建 Reducer。它要改變的組件,它獲取 state 和 action斥滤,生成新的 state
3.用 subscribe 監(jiān)聽每次修改情況
4.dispatch 執(zhí)行,reducer(currentState,action) 處理當(dāng)前 dispatch 后的傳入的 action.type 并返回給 currentState 處理后的 state轿秧,通過 currentListeners.forEach(v=>v()) 執(zhí)行監(jiān)聽函數(shù)中跌,并最后返回當(dāng)前 action 狀態(tài)。
export function createStore(reducer) {
let currentState = {};
let currentListeners = [];
// 讀取 store tree中所有state
function getState() {
return currentState
}
// 注冊(cè) listener菇篡,監(jiān)聽 state 變化
function subscribe(listener) {
// 傳入函數(shù)
currentListeners.push(listener)
}
// 分發(fā) action
function dispatch(action){
currentState = reducer(currentState,action)
currentListeners.forEach(v=>v())
return action
}
// 觸發(fā)初始狀態(tài)
dispatch({type:'@TYRMARS/Mars-Redux'})
return {getState,subscribe,dispatch}
}
二漩符、如何使用之 Redux 如何管理 state
注冊(cè) store tree
1.Redux 通過全局唯一的 store 對(duì)象管理項(xiàng)目中的 state
const store = createStore(
reducer, /* preloadedState, */
// window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__()
// 使用 chrome 的 redux-devtools 插件需要加這句話
);
2.可以通過 store 注冊(cè) listener,注冊(cè)的 listener 會(huì)在 store tree 每次變更后執(zhí)行
constructor(props) {
super(props);
......
this.storeChange = this.storeChange.bind(this);
store.subscribe(this.storeChange);
}
......
storeChange() {
this.setState(store.getState())
}
如何更新 store tree
1.store 調(diào)用 dispatch驱还,通過 action 把變更的信息傳遞給 reducer
const action = { type: 'changeInput' , value: e.target.value };
store.dispatch(action);
2.store 根據(jù) action 攜帶 type 在 reducer 中查詢變更具體要執(zhí)行的方法嗜暴,執(zhí)行后返回新的 state
export default (state = defaultState, action) => {
// Reducer 里面只能接受 state凸克,不能改變state
if (action.type === 'changeInput'){
let newState = JSON.parse(JSON.stringify(state));
newState.inputValue = action.value;
// 返回給 store倉(cāng)庫(kù)
return newState;
}
return state;
}
3.reducer 執(zhí)行后返回的新狀態(tài)會(huì)更新到 store tree 中,觸發(fā)由 store.subscribe() 注冊(cè)的所有l(wèi)istener