【每日一題】說下你對(duì)Redux的理解

人生苦短,總需要一點(diǎn)儀式感。比如學(xué)前端~
Redux
目錄:
分析
Redux 三大原則
Redux 原理
Redux 工作流程
分析
在 jQuery 時(shí)代的時(shí)候,我們是面向過程開發(fā)。隨著 react 的普及,我們提出狀態(tài)驅(qū)動(dòng) UI 的開發(fā)模式。
我們認(rèn)為:Web 應(yīng)用就是狀態(tài)與 UI 一一對(duì)應(yīng)的關(guān)系。但是隨著我們的 web 應(yīng)用日趨的復(fù)雜化,一個(gè)應(yīng)用所對(duì)應(yīng)的背后的 state 也變得越來越難以管理。而 redux 就是 web 應(yīng)用的一個(gè)狀態(tài)管理方案。Redux 是 Flux 思想的一種實(shí)現(xiàn),同時(shí)又在其基礎(chǔ)上做了改進(jìn)。其主要體現(xiàn)在:
-
單向數(shù)據(jù)流 -
Store 是唯一的數(shù)據(jù)源
Redux 三大原則
-
單一數(shù)據(jù)源 -
State 只讀 -
使用純函數(shù)來修改
Redux 原理
Redux 源碼主要分為幾個(gè)模塊文件:
-
compose.js提供從右到左進(jìn)行函數(shù)式編程 -
createStore.js提供作為生成唯一 store 的函數(shù) -
combineReducers.js提供合并多個(gè) reducer 的函數(shù),保證 store 的唯一性 -
bindActionCreators.js可以讓開發(fā)者在不直接接觸 dispatch 的前提下進(jìn)行更改 state 的操作 -
applyMiddleware.js這個(gè)方法可以通過中間件來增強(qiáng) dispatch 的功能
const actionTypes = {
ADD: 'ADD',
CHANGEINFO: 'CHANGEINFO',
}
const initState = {
info: '初始化',
}
export default function initReducer(state=initState, action) {
switch(action.type) {
case actionTypes.CHANGEINFO:
return {
...state,
info: action.preload.info || '',
}
default:
return { ...state };
}
}
export default function createStore(reducer, initialState, middleFunc) {
if (initialState && typeof initialState === 'function') {
middleFunc = initialState;
initialState = undefined;
}
let currentState = initialState;
const listeners = [];
if (middleFunc && typeof middleFunc === 'function') {
// 封裝dispatch
return middleFunc(createStore)(reducer, initialState);
}
const getState = () => {
return currentState;
}
const dispatch = (action) => {
currentState = reducer(currentState, action);
listeners.forEach(listener => {
listener();
})
}
const subscribe = (listener) => {
listeners.push(listener);
}
return {
getState,
dispatch,
subscribe
}
}
Redux 工作流程
-
const store = createStore(fn)生成數(shù)據(jù); -
action:{ type:Symbol('action001'), payload:'payload1' }定義行為; -
dispatch發(fā)起 action:store.dispatch(doSomethingfn('action001')); -
reducer處理 action,返回新的 state;
換句話解釋是:
-
首先,用戶(通過 view)發(fā)出 action,發(fā)出方式用到了dispatch方法 -
然后,store 自動(dòng)調(diào)用 reducer,并且傳入兩個(gè)參數(shù):當(dāng)前 state 和收到的 action,reducer 會(huì)返回新的state -
state 一旦有變化, store就會(huì)調(diào)用監(jiān)聽函數(shù),來更新view。
所有《每日一題》的 知識(shí)大綱索引腦圖 整理在此:https://www.yuque.com/dfe_evernote/interview/everyday
你也可以點(diǎn)擊文末的 “閱讀原文” 快速跳轉(zhuǎn)
讓我們一起攜手同走前端路!
關(guān)注公眾號(hào)回復(fù)【加群】即可
評(píng)論
圖片
表情
