Redux
- reducer: (preState: (init) , action) => newState
- const { createStore } = Redux || import { createStore } from 'redux'
const store = createStore({'reducer ()'}) - render: { … store.getState()
- store.subscribe(render)
render() - store.dispatch({...})
const counter = (state = 0, action) => {
switch (action.type) {
case 'INCREMENT':
return state + 1
case 'D........':
return state - 1
default:
return state
}
}
// pre writing
const { createStore } = Redux
const store = createStore(counter)
// now writing
// [ Implementing store from scratch ]
const createStore = (reducer) => {
let state
let listeners = []
const getState = () => state;
const dispatch = (action) => {
state = reducer(state, action)
listeners.forEach(listener => listener())
}
const subscribe = (listener) => {
listeners.push(listener)
return () => {
listeners = listeners.filter(l => l !== listener)
}
}
dispatch({})
return { getState, dispatch, subscribe }
}
const render = () => {
document.body.innerText = store.getStatr()
}
store.subscribe(render)
render()
document.addEventListener('click', () => {
store.dispatch({ type: 'IN....' })
})
Avoid Array Mutations with concat(), slice(), and ...spread
Avoid Object Mutations with Object.assign() and ...spread
define reducers
APP <= combine reducers
createStore(APP)
Redux 和 reduce 的聯(lián)系與區(qū)別
總結(jié)一下 Redux 和 reduce 的聯(lián)系與區(qū)別。
相同點:
- reduce和Redux都是對數(shù)據(jù)流進行fold(折疊、歸約)瘫证;
- 兩者都包含一個累積器(reducer)((a, b) -> a VS (state, action) -> state )和初始值(initialValue VS initialState ),兩者都接受一個抽象意義上的列表(list VS stream )豆励。
不同點:
- reduce:接收一個有限長度的普通列表作為參數(shù),對列表中的元素從前往后依次累積,并輸出最終的累積結(jié)果。
- Redux:由于基于時間的事件流是一個無限長的抽象列表傲宜,我們無法顯式地將事件流作為參數(shù)傳給Redux,也無法返回最終的累積結(jié)果(事件流無限長)夫啊。所以我們將事件流抽離出來函卒,通過 dispatch 主動地向 reducer 累積器 push action,通過 getState 觀察當(dāng)前的累積值(中間的累積過程)撇眯。
- 從冷报嵌、熱信號的角度看,reduce 的輸入相當(dāng)于冷信號熊榛,累積器需要主動拉让(pull)輸入列表中的元素進行累積;而Redux的輸入(事件流)相當(dāng)于熱信號玄坦,需要外部主動調(diào)用 dispatch(action) 將當(dāng)前元素push給累積器血筑。
由上可知,Redux將所有的事件都抽象為 action煎楣,無論是用戶點擊豺总、Ajax請求還是頁面刷新,只要有新的事件發(fā)生择懂,我們就會 dispatch 一個 action給 reducer喻喳,并結(jié)合上一次的狀態(tài)計算出本次狀態(tài)。抽象出來的統(tǒng)一的事件接口休蟹,簡化了處理事件的復(fù)雜度沸枯。
Redux還規(guī)范了事件流——單向事件流日矫,事件 action 只能由 dispatch函數(shù)派發(fā),并且只能通過 reducer 更新系統(tǒng)(網(wǎng)頁)的狀態(tài) state绑榴,然后等待下一次事件哪轿。這種單向事件流機制能夠進一步簡化事件管理的復(fù)雜度,并且有較好的擴展性翔怎,可以在事件流動過程中插入 middleware窃诉,比如日志記錄、thunk赤套、異步處理等飘痛,進而大大增強事件處理的靈活性。