24行JavaScript代碼實(shí)現(xiàn)Redux的方法實(shí)例
前言
Redux是迄今為止創(chuàng)建的最重要的JavaScript庫(kù)之一,靈感來(lái)源于以前的藝術(shù)比如Flux和Elm,Redux通過(guò)引入一個(gè)包含三個(gè)簡(jiǎn)單要點(diǎn)的可伸縮體系結(jié)構(gòu),使得JavaScript函數(shù)式編程成為可能。如果你是初次接觸Redux,可以考慮先閱讀官方文檔。
1. Redux大多是規(guī)約
考慮如下這個(gè)使用了Redux架構(gòu)的簡(jiǎn)單的計(jì)數(shù)器應(yīng)用。如果你想跳過(guò)的話可以直接查看Github Repo。
1.1 State存儲(chǔ)在一棵樹中
該應(yīng)用程序的狀態(tài)看起來(lái)如下:
const initialState = { count: 0 };
1.2 Action聲明狀態(tài)更改
根據(jù)Redux規(guī)約,我們不直接修改(突變)狀態(tài)。
// 在Redux應(yīng)用中不要做如下操作 state.count = 1;
相反,我們創(chuàng)建在應(yīng)用中用戶可能用到的所有行為。
const actions = { increment: { type: 'INCREMENT' }, decrement: { type: 'DECREMENT' } };
1.3 Reducer解釋行為并更新狀態(tài)
在最后一個(gè)架構(gòu)部分我們叫做Reduer,其作為一個(gè)純函數(shù),它基于以前的狀態(tài)和行為返回狀態(tài)的新副本。
- 如果increment被觸發(fā),則增加state.count
- 如果decrement被觸發(fā),則減少state.count
const countReducer = (state = initialState, action) => { switch (action.type) { case actions.increment.type: return { count: state.count + 1 }; case actions.decrement.type: return { count: state.count - 1 }; default: return state; } };
1.4 目前為止還沒有Redux
你注意到了嗎?到目前為止我們甚至還沒有接觸到Redux庫(kù),我們僅僅只是創(chuàng)建了一些對(duì)象和函數(shù),這就是為什么我稱其為"大多是規(guī)約",90%的Redux應(yīng)用其實(shí)并不需要Redux。
2. 開始實(shí)現(xiàn)Redux
要使用這種架構(gòu),我們必須要將它放入到一個(gè)store當(dāng)中,我們將僅僅實(shí)現(xiàn)一個(gè)函數(shù):createStore。使用方式如下:
import { createStore } from 'redux' const store = createStore(countReducer); store.subscribe(() => { console.log(store.getState()); }); store.dispatch(actions.increment); // logs { count: 1 } store.dispatch(actions.increment); // logs { count: 2 } store.dispatch(actions.decrement); // logs { count: 1 }
下面這是我們的初始化樣板代碼,我們需要一個(gè)監(jiān)聽器列表listeners和reducer提供的初始化狀態(tài)。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); }
無(wú)論何時(shí)某人訂閱了我們的store,那么他將會(huì)被添加到listeners數(shù)組中。這是非常重要的,因?yàn)槊看萎?dāng)某人在派發(fā)(dispatch)一個(gè)動(dòng)作(action)的時(shí)候,所有的listeners都需要在此次事件循環(huán)中被通知到。調(diào)用yourReducer函數(shù)并傳入一個(gè)undefined和一個(gè)空對(duì)象將會(huì)返回一個(gè)initialState,這個(gè)值也就是我們?cè)谡{(diào)用store.getState()時(shí)的返回值。既然說(shuō)到這里了,我們就來(lái)創(chuàng)建這個(gè)方法。
2.1 store.getState()
這個(gè)函數(shù)用于從store中返回最新的狀態(tài),當(dāng)用戶每次點(diǎn)擊一個(gè)按鈕的時(shí)候我們都需要最新的狀態(tài)來(lái)更新我們的視圖。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState }; }
2.2 store.dispatch()
這個(gè)函數(shù)使用一個(gè)action作為其入?yún)ⅲ⑶覍⑦@個(gè)action和currentState反饋給yourReducer來(lái)獲取一個(gè)新的狀態(tài),并且dispatch方法還會(huì)通知到每一個(gè)訂閱了當(dāng)前store的監(jiān)聽者。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState, dispatch: (action) => { currentState = yourReducer(currentState, action); listeners.forEach((listener) => { listener(); }); } }; };
2.3 store.subscribe(listener)
這個(gè)方法使得你在當(dāng)store接收到一個(gè)action的時(shí)候能夠被通知到,可以在這里調(diào)用store.getState()來(lái)獲取最新的狀態(tài)并更新UI。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState, dispatch: (action) => { currentState = yourReducer(currentState, action); listeners.forEach((listener) => { listener(); }); }, subscribe: (newListener) => { listeners.push(newListener); const unsubscribe = () => { listeners = listeners.filter((l) => l !== newListener); }; return unsubscribe; } }; };
同時(shí)subscribe函數(shù)返回了另一個(gè)函數(shù)unsubscribe,這個(gè)函數(shù)允許你當(dāng)不再對(duì)store的更新感興趣的時(shí)候能夠取消訂閱。
3. 整理代碼
現(xiàn)在我們添加按鈕的邏輯,來(lái)看看最后的源代碼:
// 簡(jiǎn)化版createStore函數(shù) const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState, dispatch: (action) => { currentState = yourReducer(currentState, action); listeners.forEach((listener) => { listener(); }); }, subscribe: (newListener) => { listeners.push(newListener); const unsubscribe = () => { listeners = listeners.filter((l) => l !== newListener); }; return unsubscribe; } }; }; // Redux的架構(gòu)組成部分 const initialState = { count: 0 }; const actions = { increment: { type: 'INCREMENT' }, decrement: { type: 'DECREMENT' } }; const countReducer = (state = initialState, action) => { switch (action.type) { case actions.increment.type: return { count: state.count + 1 }; case actions.decrement.type: return { count: state.count - 1 }; default: return state; } }; const store = createStore(countReducer); // DOM元素 const incrementButton = document.querySelector('.increment'); const decrementButton = document.querySelector('.decrement'); // 給按鈕添加點(diǎn)擊事件 incrementButton.addEventListener('click', () => { store.dispatch(actions.increment); }); decrementButton.addEventListener('click', () => { store.dispatch(actions.decrement); }); // 初始化UI視圖 const counterDisplay = document.querySelector('h1'); counterDisplay.innerHTML = parseInt(initialState.count); // 派發(fā)動(dòng)作的時(shí)候跟新UI store.subscribe(() => { const state = store.getState(); counterDisplay.innerHTML = parseInt(state.count); });
我們?cè)俅慰纯醋詈蟮囊晥D效果:
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對(duì)腳本之家的支持。
原文: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/
作者:Yazeed Bzadough
譯者:小維FE
相關(guān)文章
JS動(dòng)態(tài)顯示倒計(jì)時(shí)效果
這篇文章主要介紹了JS實(shí)現(xiàn)倒計(jì)時(shí)效果動(dòng)態(tài)顯示倒計(jì)時(shí)功能,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-12-12js實(shí)現(xiàn)省級(jí)聯(lián)動(dòng)(數(shù)據(jù)結(jié)構(gòu)優(yōu)化)
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)省級(jí)聯(lián)動(dòng),數(shù)據(jù)結(jié)構(gòu)優(yōu)化,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-07-07JavaScript實(shí)現(xiàn)模仿桌面窗口的方法
這篇文章主要介紹了JavaScript實(shí)現(xiàn)模仿桌面窗口的方法,可實(shí)現(xiàn)模仿桌面窗口的打開、關(guān)閉、移動(dòng)、縮放及最大化、最小化等功能,需要的朋友可以參考下2015-07-07微信小程序遍歷Echarts圖表實(shí)現(xiàn)多個(gè)餅圖
這篇文章主要介紹了微信小程序遍歷Echarts圖表實(shí)現(xiàn)多個(gè)餅圖,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-04-04KnockoutJS 3.X API 第四章之表單value綁定
Knockout是一個(gè)以數(shù)據(jù)模型(data model)為基礎(chǔ)的能夠幫助你創(chuàng)建富文本,響應(yīng)顯示和編輯用戶界面的JavaScript類庫(kù)。這篇文章主要介紹了KnockoutJS 3.X API 第四章之表單value綁定的相關(guān)資料,需要的朋友可以參考下2016-10-10Android 自定義view仿微信相機(jī)單擊拍照長(zhǎng)按錄視頻按鈕
這篇文章主要介紹了Android 自定義view仿微信相機(jī)單擊拍照長(zhǎng)按錄視頻按鈕,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值 ,需要的朋友可以參考下2019-07-07