24行JavaScript代碼實現(xiàn)Redux的方法實例
前言
Redux是迄今為止創(chuàng)建的最重要的JavaScript庫之一,靈感來源于以前的藝術比如Flux和Elm,Redux通過引入一個包含三個簡單要點的可伸縮體系結構,使得JavaScript函數(shù)式編程成為可能。如果你是初次接觸Redux,可以考慮先閱讀官方文檔。
1. Redux大多是規(guī)約
考慮如下這個使用了Redux架構的簡單的計數(shù)器應用。如果你想跳過的話可以直接查看Github Repo。
1.1 State存儲在一棵樹中
該應用程序的狀態(tài)看起來如下:
const initialState = { count: 0 };
1.2 Action聲明狀態(tài)更改
根據(jù)Redux規(guī)約,我們不直接修改(突變)狀態(tài)。
// 在Redux應用中不要做如下操作 state.count = 1;
相反,我們創(chuàng)建在應用中用戶可能用到的所有行為。
const actions = { increment: { type: 'INCREMENT' }, decrement: { type: 'DECREMENT' } };
1.3 Reducer解釋行為并更新狀態(tài)
在最后一個架構部分我們叫做Reduer,其作為一個純函數(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庫,我們僅僅只是創(chuàng)建了一些對象和函數(shù),這就是為什么我稱其為"大多是規(guī)約",90%的Redux應用其實并不需要Redux。
2. 開始實現(xiàn)Redux
要使用這種架構,我們必須要將它放入到一個store當中,我們將僅僅實現(xiàn)一個函數(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 }
下面這是我們的初始化樣板代碼,我們需要一個監(jiān)聽器列表listeners和reducer提供的初始化狀態(tài)。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); }
無論何時某人訂閱了我們的store,那么他將會被添加到listeners數(shù)組中。這是非常重要的,因為每次當某人在派發(fā)(dispatch)一個動作(action)的時候,所有的listeners都需要在此次事件循環(huán)中被通知到。調用yourReducer函數(shù)并傳入一個undefined和一個空對象將會返回一個initialState,這個值也就是我們在調用store.getState()時的返回值。既然說到這里了,我們就來創(chuàng)建這個方法。
2.1 store.getState()
這個函數(shù)用于從store中返回最新的狀態(tài),當用戶每次點擊一個按鈕的時候我們都需要最新的狀態(tài)來更新我們的視圖。
const createStore = (yourReducer) => { let listeners = []; let currentState = yourReducer(undefined, {}); return { getState: () => currentState }; }
2.2 store.dispatch()
這個函數(shù)使用一個action作為其入?yún)?,并且將這個action和currentState反饋給yourReducer來獲取一個新的狀態(tài),并且dispatch方法還會通知到每一個訂閱了當前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)
這個方法使得你在當store接收到一個action的時候能夠被通知到,可以在這里調用store.getState()來獲取最新的狀態(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; } }; };
同時subscribe函數(shù)返回了另一個函數(shù)unsubscribe,這個函數(shù)允許你當不再對store的更新感興趣的時候能夠取消訂閱。
3. 整理代碼
現(xià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的架構組成部分 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'); // 給按鈕添加點擊事件 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ā)動作的時候跟新UI store.subscribe(() => { const state = store.getState(); counterDisplay.innerHTML = parseInt(state.count); });
我們再次看看最后的視圖效果:
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
原文: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/
作者:Yazeed Bzadough
譯者:小維FE
相關文章
js實現(xiàn)省級聯(lián)動(數(shù)據(jù)結構優(yōu)化)
這篇文章主要為大家詳細介紹了js實現(xiàn)省級聯(lián)動,數(shù)據(jù)結構優(yōu)化,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-07-07KnockoutJS 3.X API 第四章之表單value綁定
Knockout是一個以數(shù)據(jù)模型(data model)為基礎的能夠幫助你創(chuàng)建富文本,響應顯示和編輯用戶界面的JavaScript類庫。這篇文章主要介紹了KnockoutJS 3.X API 第四章之表單value綁定的相關資料,需要的朋友可以參考下2016-10-10Android 自定義view仿微信相機單擊拍照長按錄視頻按鈕
這篇文章主要介紹了Android 自定義view仿微信相機單擊拍照長按錄視頻按鈕,本文通過實例代碼給大家介紹的非常詳細,具有一定的參考借鑒價值 ,需要的朋友可以參考下2019-07-07