如何在24行JavaScript中實現Redux

90% convention, 10% library.

90%的慣例,10%的圖書館。

Redux is among the most important JavaScript libraries ever created. Inspired by prior art like Flux and Elm, Redux put JavaScript functional programming on the map by introducing a scalable architecture of three simple points.

Redux是有史以來最重要JavaScript庫之一。 受Flux和Elm等現有技術的啟發,Redux通過引入三個簡單點的可伸縮體系結構,將JavaScript函數式編程放在了地圖上。

If you're new to Redux, consider reading the official docs first.

如果您不熟悉Redux,請考慮先閱讀官方文檔 。

Redux通常是慣例 (Redux Is Mostly Convention)

Consider this simple counter application that uses the Redux architecture. If you'd like to jump ahead check out the Github repo for it.

考慮使用Redux架構的簡單計數器應用程序。 如果您想繼續前進,請查看Github存儲庫 。

redux-counter-app-demo

國家生活在一棵樹上 (State lives in a single tree)

The application's state looks like this.

應用程序的狀態如下所示。

const initialState = { count: 0 };

動作聲明狀態更改 (Actions declare state changes)

By Redux convention, I do not directly modify (mutate) the state.

根據Redux約定, 我不直接修改(更改)狀態。

// DON'T do this in a Redux app
state.count = 1;

Instead I create all the actions the user may leverage in the application.

相反,我創建了用戶可以在應用程序中利用的所有操作。

const actions = {increment: { type: 'INCREMENT' },decrement: { type: 'DECREMENT' }
};

Reducer解釋動作并更新狀態 (Reducer interprets action and updates state)

The last architectural piece calls for a reducer, a pure function that returns a new copy of your state based on the previous state and action.

最后一個體系結構部分需要一個reducer,這是一個純函數,它根據先前的狀態和操作返回狀態的新副本。

  • If increment is fired, increment state.count.

    如果increment被激發,增量state.count

  • If decrement is fired, decrement state.count.

    如果decrement ,則遞減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;}
};

到目前為止還沒有Redux (No Redux so far)

Did you notice that we haven't touched the Redux library yet? We've just created some objects and a function. This is what I mean by "mostly convention", 90% of Redux doesn't require Redux!

您是否注意到我們還沒有涉及Redux庫? 我們剛剛創建了一些對象和一個函數。 這就是我所說的“主要是慣例”,Redux的90%不需要Redux!

讓我們實現Redux (Let's implement Redux)

To put this architecture to use, we must plug it into a store. We'll implement just one function–createStore.

要使用此架構,我們必須將其插入商店。 我們將僅實現一個功能– createStore

It's used like this.

這樣使用。

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 }

And here's our initial boilerplate. We'll need a list of listeners and the initial state supplied by the reducer.

這是我們最初的樣板。 我們需要一個偵聽器列表以及化簡器提供的初始狀態。

const createStore = (yourReducer) => {let listeners = [];let currentState = yourReducer(undefined, {});
}

Whenever someone subscribes to our store, they get added to the listeners array. The is important because every time someone dispatches an action, all the listeners must be notified in a loop.

每當有人訂閱我們的商店時,他們就會被添加到listeners數組中。 這樣做很重要,因為每次有人分派操作時,都必須在循環中通知所有listeners

Calling yourReducer with undefined and an empty object returns the initialState we installed up above. This gives us a proper value to return when we call store.getState(). Speaking of which, let's create that method.

undefined和一個空對象調用yourReducer返回我們在上面安裝的initialState 。 這給我們一個適當的值,當我們調用store.getState()時可以返回。 說到這,讓我們創建該方法。

store.getState() (store.getState())

This is a function that returns the latest state from the store. We'll need this to update our UI every time the user clicks a button.

此函數可從商店返回最新狀態。 每次用戶單擊按鈕時,我們都需要用它來更新我們的UI。

const createStore = (yourReducer) => {let listeners = [];let currentState = yourReducer(undefined, {});return {getState: () => currentState};
}

store.dispatch(動作) (store.dispatch(action))

This is a function that takes an action as a parameter. It feeds that action and the currentState to yourReducer to get a new state. Then dispatch notifies everyone subscribed to the store.

該函數將action作為參數。 它將該actioncurrentState饋送到yourReducer以獲取狀態。 然后dispatch通知每個訂閱該store

const createStore = (yourReducer) => {let listeners = [];let currentState = yourReducer(undefined, {});return {getState: () => currentState,dispatch: (action) => {currentState = yourReducer(currentState, action);listeners.forEach((listener) => {listener();});}};
};

store.subscribe(偵聽器) (store.subscribe(listener))

This is a function that lets you be notified when the store receives an action It's good to use store.getState() in here to get your latest state and update your UI.

此功能可讓您在商店收到操作時得到通知。在這里使用store.getState()來獲取最新狀態并更新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 returns a function called unsubscribe that you can call when you're no longer interested in listening to the store's updates.

subscribe返回一個稱為unsubscribe的函數,您不再對收聽商店的更新感興趣時可以調用該函數。

現在都在一起了 (All Together Now)

Let's hook this up to our buttons and view the final source code.

讓我們將其掛接到我們的按鈕上,并查看最終的源代碼。

// simplified createStore function
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 architecture pieces
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 elements
const incrementButton = document.querySelector('.increment');
const decrementButton = document.querySelector('.decrement');// Wire click events to actions
incrementButton.addEventListener('click', () => {store.dispatch(actions.increment);
});decrementButton.addEventListener('click', () => {store.dispatch(actions.decrement);
});// Initialize UI display
const counterDisplay = document.querySelector('h1');
counterDisplay.innerHTML = parseInt(initialState.count);// Update UI when an action fires
store.subscribe(() => {const state = store.getState();counterDisplay.innerHTML = parseInt(state.count);
});

And once again here's our final UI.

這又是我們的最終用戶界面。

redux-counter-app-demo

If you're interested in the HTML/CSS I used, here's the GitHub repo again!

如果您對我使用HTML / CSS感興趣,請再次訪問GitHub存儲庫 !

需要免費輔導嗎? (Want Free Coaching?)

If you'd like to schedule a free call to discuss Front-End development questions regarding code, interviews, career, or anything else follow me on Twitter and DM me.

如果您想安排免費電話討論有關代碼,面試,職業或其他方面的前端開發問題,請在Twitter和DM me上關注我 。

After that if you enjoy our first meeting, we can discuss an ongoing coaching to help you reach your Front-End development goals!

之后,如果您喜歡我們的第一次會議,我們可以討論一個持續的教練,以幫助您實現前端開發目標!

貢獻您的力量 (Wear Your Contributions)

If you're coding every day, especially if you're committing to GitHub, wouldn't it be cool to wear that contribution map for all to see?

如果您每天都在編寫代碼,特別是如果您要提交到GitHub,那么穿上所有人都能看到的貢獻圖會不會很酷?

Gitmerch.com lets you print a t-shirt of your GitHub contribution map! Use the code, Yazeed, at checkout for a discount.

Gitmerch.com可讓您打印GitHub貢獻圖的T恤! 結帳時使用代碼Yazeed可獲得折扣。

git-merch-screenshot-1-1

git-merch-screenshot-2-1

謝謝閱讀 (Thanks for reading)

For more content like this, check out https://yazeedb.com!

有關更多內容,請訪問https://yazeedb.com!

Until next time!

直到下一次!

翻譯自: https://www.freecodecamp.org/news/redux-in-24-lines-of-code/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391135.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391135.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391135.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

卡方檢驗 原理_什么是卡方檢驗及其工作原理?

卡方檢驗 原理As a data science engineer, it’s imperative that the sample data set which you pick from the data is reliable, clean, and well tested for its usability in machine learning model building.作為數據科學工程師,當務之急是從數據中挑選出的…

Web UI 設計(網頁設計)命名規范

Web UI 設計命名規范 一.網站設計及基本框架結構: 1. Container“container“ 就是將頁面中的所有元素包在一起的部分,這部分還可以命名為: “wrapper“, “wrap“, “page“.2. Header“header” 是網站頁面的頭部區域,一般來講,它包含…

leetcode 1486. 數組異或操作(位運算)

給你兩個整數,n 和 start 。 數組 nums 定義為:nums[i] start 2*i(下標從 0 開始)且 n nums.length 。 請返回 nums 中所有元素按位異或(XOR)后得到的結果。 示例 1: 輸入:n …

27個機器學習圖表翻譯_使用機器學習的信息圖表信息組織

27個機器學習圖表翻譯Infographics are crucial for presenting information in a more digestible fashion to the audience. With their usage being expanding to many (if not all) professions like journalism, science, and research, advertisements, business, the re…

在HTML中使用javascript (js高級程序設計)

在HTML中使用javascript 剛開始入門的時候覺得關于應用以及在html中只用javascript很簡單,不需要進行學習。我又開始重溫了一下紅寶書,覺得還是有必要進行學習的。這是一個筆記! script 元素插入有多種方式 屬性使用方式async延遲腳本&#x…

大數據新手之路二:安裝Flume

Ubuntu16.04Flume1.8.0 1.下載apache-flume-1.8.0-bin.tar.gz http://flume.apache.org/download.html 2.解壓到/usr/local/flume中 3.設置配置文件/etc/profile文件,增加flume的路徑 ①vi /etc/profile export FLUME_HOME/usr/local/flume export PATH$PATH:$FLUME…

leetcode 1723. 完成所有工作的最短時間(二分+剪枝+回溯)

給你一個整數數組 jobs ,其中 jobs[i] 是完成第 i 項工作要花費的時間。 請你將這些工作分配給 k 位工人。所有工作都應該分配給工人,且每項工作只能分配給一位工人。工人的 工作時間 是完成分配給他們的所有工作花費時間的總和。請你設計一套最佳的工作…

異步解耦_如何使用異步生成器解耦業務邏輯

異步解耦Async generators are new in JavaScript. They are a remarkable extension. They provide a simple but very powerful tool for splitting programs into smaller parts, making sources easier to write, read, maintain and test.異步生成器是JavaScript中的新增功…

函數的定義,語法,二維數組,幾個練習題

1、請將’A’,’B’,’C’存入數組,然后再輸出2、請將”我” “愛” “你”存入數組,然后正著和反著輸出3、輸入10個整數存入數組,然后復制到b數組中輸出4、定義一個長度為10的數組,循環輸入10個整數。 然后將輸入一個整數&#x…

leetcode 1482. 制作 m 束花所需的最少天數(二分查找)

給你一個整數數組 bloomDay,以及兩個整數 m 和 k 。 現需要制作 m 束花。制作花束時,需要使用花園中 相鄰的 k 朵花 。 花園中有 n 朵花,第 i 朵花會在 bloomDay[i] 時盛開,恰好 可以用于 一束 花中。 請你返回從花園中摘 m 束…

算法訓練營 重編碼_編碼訓練營手冊:沉浸式工程程序介紹

算法訓練營 重編碼Before you spend thousands of dollars and several months of your life on a coding bootcamp, spend 30 minutes reading this handbook.在花費數千美元和一生中的幾個月時間參加編碼訓練營之前,請花30分鐘閱讀本手冊。 這本手冊適用于誰&…

面向Tableau開發人員的Python簡要介紹(第4部分)

用PYTHON探索數據 (EXPLORING DATA WITH PYTHON) Between data blends, joins, and wrestling with the resulting levels of detail in Tableau, managing relationships between data can be tricky.在數據混合,聯接以及在Tableau中產生的詳細程度之間進行搏斗之間…

bzoj 4552: [Tjoi2016Heoi2016]排序

Description 在2016年,佳媛姐姐喜歡上了數字序列。因而他經常研究關于序列的一些奇奇怪怪的問題,現在他在研究一個難題,需要你來幫助他。這個難題是這樣子的:給出一個1到n的全排列,現在對這個全排列序列進行m次局部排序…

oracle之 手動創建 emp 表 與 dept 表

說明: 有時候我們需要通用的實驗數據,emp表 與 dept表 但是數據庫中有沒有。 這時,我們可以手動創建。 -- 創建表與數據CREATE TABLE EMP(EMPNO NUMBER(4) NOT NULL, ENAME VARCHAR2(10), JOB VARCHAR2(9), MGR NUMBER(4), HIREDATE DATE, S…

深入理解InnoDB(8)—單表訪問

1. 訪問方法 MySQL把執行查詢語句的方式稱之為訪問方法或者訪問類型。 而訪問方法大致分為兩類 全表掃描索引 而進行細分的話可以分為以下幾類 (為了方便說明,先建一個表) CREATE TABLE single_table (id INT NOT NULL AUTO_INCREMENT,key…

蝙蝠俠遙控器pcb_通過蝙蝠俠從Circle到ML:第二部分

蝙蝠俠遙控器pcbView Graph查看圖 背景 (Background) Wait! Isn’t the above equation different from what we found last time? Yup, very different but still looks exactly the same or maybe a bit better. Just in case you are wondering what I am talking about, p…

camera驅動框架分析(上)

前言 camera驅動框架涉及到的知識點比較多,特別是camera本身的接口就有很多,有些是直接連接到soc的camif口上的,有些是通過usb接口導出的,如usb camera。我這里主要討論前者,也就是與soc直連的。我認為凡是涉及到usb的…

工程項目管理需要注意哪些問題

在社會科學技術發展和市場經濟繁榮昌盛的今天,為更好的滿足社會人性化的需求,建設施工企業在建筑施工、布局以及內部運行都給予了落實。而工程項目是建筑施工企業面向建筑市場的窗口,是企業建筑活動的前沿陣地,管理需更嚴謹。 雖說…

leetcode 872. 葉子相似的樹(dfs)

請考慮一棵二叉樹上所有的葉子,這些葉子的值按從左到右的順序排列形成一個 葉值序列 。 舉個例子,如上圖所示,給定一棵葉值序列為 (6, 7, 4, 9, 8) 的樹。 如果有兩棵二叉樹的葉值序列是相同,那么我們就認為它們是 葉相似 的。 …

探索感染了COVID-19的動物的數據

數據 (The data) With the number of cases steadily rising day by day, COVID-19 has been pretty much in the headlines of every newspaper known to man. Despite the massive amount of attention, a topic that has remained mostly untouched (some exceptions being …