24行JavaScript代碼實(shí)現(xiàn)Redux的方法實(shí)例
前言
Redux是迄今為止創(chuàng)建的最重要的JavaScript庫之一,靈感來源于以前的藝術(shù)比如Flux和Elm,Redux通過引入一個包含三個簡單要點(diǎn)的可伸縮體系結(jié)構(gòu),使得JavaScript函數(shù)式編程成為可能。如果你是初次接觸Redux,可以考慮先閱讀官方文檔。
1. Redux大多是規(guī)約
考慮如下這個使用了Redux架構(gòu)的簡單的計(jì)數(shù)器應(yīng)用。如果你想跳過的話可以直接查看Github Repo。
1.1 State存儲在一棵樹中
該應(yīng)用程序的狀態(tà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òu)部分我們叫做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應(yīng)用其實(shí)并不需要Redux。
2. 開始實(shí)現(xiàn)Redux
要使用這種架構(gòu),我們必須要將它放入到一個store當(dāng)中,我們將僅僅實(shí)現(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, {});
}
無論何時(shí)某人訂閱了我們的store,那么他將會被添加到listeners數(shù)組中。這是非常重要的,因?yàn)槊看萎?dāng)某人在派發(fā)(dispatch)一個動作(action)的時(shí)候,所有的listeners都需要在此次事件循環(huán)中被通知到。調(diào)用yourReducer函數(shù)并傳入一個undefined和一個空對象將會返回一個initialState,這個值也就是我們在調(diào)用store.getState()時(shí)的返回值。既然說到這里了,我們就來創(chuàng)建這個方法。
2.1 store.getState()
這個函數(shù)用于從store中返回最新的狀態(tài),當(dāng)用戶每次點(diǎn)擊一個按鈕的時(shí)候我們都需要最新的狀態(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方法還會通知到每一個訂閱了當(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)
這個方法使得你在當(dāng)store接收到一個action的時(shí)候能夠被通知到,可以在這里調(diào)用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;
}
};
};
同時(shí)subscribe函數(shù)返回了另一個函數(shù)unsubscribe,這個函數(shù)允許你當(dāng)不再對store的更新感興趣的時(shí)候能夠取消訂閱。
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的架構(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ā)動作的時(shí)候跟新UI
store.subscribe(() => {
const state = store.getState();
counterDisplay.innerHTML = parseInt(state.count);
});
我們再次看看最后的視圖效果:

總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,謝謝大家對腳本之家的支持。
原文: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/
作者:Yazeed Bzadough
譯者:小維FE
相關(guān)文章
layUI實(shí)現(xiàn)三級導(dǎo)航菜單效果
這篇文章主要為大家詳細(xì)介紹了layUI實(shí)現(xiàn)三級導(dǎo)航菜單效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-07-07
Javascript aop(面向切面編程)之a(chǎn)round(環(huán)繞)分析
這篇文章主要介紹了Javascript aop(面向切面編程)之a(chǎn)round(環(huán)繞) ,需要的朋友可以參考下2015-05-05

