具象化一下,最多見的例子,咱們平時都訂閱過公衆號對吧,你訂閱了某個公衆號後,當你訂閱的公衆號發佈什麼通知或推文,你這邊就會收到。你做爲一個觀察者,訂閱後,css
文章地址:https://shudong.wang/article/111html
咱們先用原生代碼實現一個觀察者模式
返回三個函數
getState 獲取狀態 dispatch 用來觸發Action subscribe 訂閱
createStore 工廠函數
const createStore = (reducer) => { let state; let listeners = []; // 純函數返回當前的state const getState = () => state // 定義一個dispatch 用來觸發action const dispatch = (action) => { //經過調用傳進來的reducer函數來修改state //返回新的狀態並賦值給state state = reducer(state, action); } //訂閱狀態 const subscribe = function (data) { //先把此監聽 加到數組中 listeners.push(data); //返回一個函數,當調用它的時候將此監聽函數從監聽數組移除 return function () { listeners = listeners.filter(v => v != data); } } //初始化的時候 調用一次dispatch給state賦一個默認值 dispatch({ type: 'stark' }) // 初始化全局狀態 // 返回三個方法 return { getState, dispatch, subscribe } }
const reducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1 case 'MIN': return state - 1 default: return 10 } }
let store = createStore(reducer);
const init = store.getState()
const render = () => { document.body.innerText = store.getState() }
store.subscribe(render);
render();
let INCREASE_ACTION = { type: 'INCREMENT' };
document.addEventListener('click', function (e) { //觸發一個Action store.dispatch(INCREASE_ACTION); })
http://github.com/wsdo/redux.gitgit
經過這個例子,咱們慢慢理解redux 會有一個初步認識
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/babel-polyfill/7.0.0-beta.44/polyfill.min.js"></script> </head> <body> </body> <script> const createStore = (reducer) => { let state; // 定義存儲的state let listeners = []; const getState = () => state; const dispatch = (action) => { console.log('====================================') console.log('action', action) console.log('state', state) console.log('====================================') state = reducer(state, action); // listeners.forEach(listener => listener()); } const subscribe = function (listener) { listeners.push(listener); console.log('====================================') console.log(listeners) console.log('====================================') return function () { listeners = listeners.filter(v => v != listener); } } dispatch({ type: 'stark' }) // 初始化全局狀態 return { getState, dispatch, subscribe } } const reducer = (state = 0, action) => { switch (action.type) { case 'INCREMENT': return state + 1 case 'MIN': return state - 1 default: return 10 } } let store = createStore(reducer); const init = store.getState() console.log('====================================') console.log(init) console.log('====================================') //把數據渲染到界面上 const render = () => { document.body.innerText = store.getState() } // 訂閱 store.subscribe(render); render(); var INCREASE_ACTION = { type: 'INCREMENT' }; document.addEventListener('click', function (e) { //觸發一個Action store.dispatch(INCREASE_ACTION); }) </script> </html>