如何在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.mzph.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” 是网站页面的头部区域,一般来讲,它包含…

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…

面向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中产生的详细程度之间进行搏斗之间…

蝙蝠侠遥控器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的…

探索感染了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 …

Facebook哭晕在厕所,调查显示用VR体验社交的用户仅为19%

美国娱乐软件协会ESA调查显示,有74%的用户使用VR玩游戏,而仅有19%的用户会用VR进行社交。 当我们说到VR社交,必然离不开Facebook。在刚刚结束的F8大会上,小扎展示了VR社交平台Facebook Spaces测试版,巧的是此前也有好…

解决Javascript疲劳的方法-以及其他所有疲劳

Learn your fundamentals, and never worry again. 了解您的基础知识,再也不用担心。 新工具让我担心 (New Tools Worry Me) When JavaScripts shiny tool of the day comes out, I sometimes overreact. 当JavaScript一天一度的闪亮工具问世时,我有时R…

已知两点坐标拾取怎么操作_已知的操作员学习-第4部分

已知两点坐标拾取怎么操作有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) These are the lecture notes for FAU’s YouTube Lecture “Deep Learning”. This is a full transcript of the lecture video & matching slides. We hope, you enjoy this as mu…

北京供销大数据集团发布SinoBBD Cloud 一体化推动产业云发展

9月5日,第五届全球云计算大会在上海世博展览馆盛大开幕,国内外顶尖企业汇聚一堂,新一代云计算技术产品纷纷亮相。作为国内领先的互联网基础服务提供商,北京供销大数据集团(以下简称“SinoBBD”)受邀参加此次大会,并正式…

“陪护机器人”研报:距离真正“陪护”还差那么一点

一款有“缺陷”的机器人,怎能做到真正的“陪护”? 近日,鼎盛智能发布了一款名为Ibotn的(爱蹦)幼儿陪伴机器人,核心看点就是通过人脸识别、场景识别等计算机视觉技术来实现机器人对儿童的陪护。不过&#xf…

【转】消息队列应用场景

一、消息队列概述 消息队列中间件是分布式系统中重要的组件,主要解决应用耦合,异步消息,流量削锋等问题。实现高性能,高可用,可伸缩和最终一致性架构。是大型分布式系统不可缺少的中间件。 目前在生产环境,…

lime 模型_使用LIME的糖尿病预测模型解释— OneZeroBlog

lime 模型Article outline文章大纲 Introduction 介绍 Data Background 资料背景 Aim of the article 本文的目的 Exploratory analysis 探索性分析 Training a Random Forest Model 训练随机森林模型 Global Importance 全球重要性 Local Importance 当地重要性 介绍 (Introd…

Linux第三周作业

1.三个法宝 ①存储程序计算机工作模型,计算机系统最最基础性的逻辑结构; ②函数调用堆栈,堆栈完成了计算机的基本功能:函数的参数传递机制和局部变量存取 ; ③中断,多道程序操作系统的基点,没有…

RESTful API浅谈

2019独角兽企业重金招聘Python工程师标准>>> 上半年时候,部门有组织的讨论了一下实践微服务的技术话题,主要内容是SOA服务和微服务各自的优势和难点,其中有提到关于RESTful API设计方法。 正好最近在深入的学习HTTP协议&#xff0…

变量的作用域和生存期:_生存分析简介:

变量的作用域和生存期:In the previous article, I have described the Kaplan-Meier estimator. To give a quick recap, it is a non-parametric method to approximating the true survival function. This time, I will focus on another approach to visualizing a surviv…

您的网卡配置暂不支持1000M宽带说明

国内宽带网速越来越快,运营商更是在今年初纷纷推进千兆宽带业务。为了让用户更好地了解网络状况,360宽带测速器发布新版,优化了宽带测速范围,可有效支持最高1000M的带宽测量。此外,宽带测速器能检测用户网卡…

永无止境_永无止境地死:

永无止境Wir befinden uns mitten in der COVID-19-Pandemie und damit auch im Mittelpunkt einer medialen Geschichte, die durch eine noch nie dagewesene Komplexitt und Dynamik gekennzeichnet ist. Wie kann Informationsdesign helfen, diese Explosion von Nachrich…

HDU4612 Warm up —— 边双联通分量 + 重边 + 缩点 + 树上最长路

题目链接:http://acm.split.hdu.edu.cn/showproblem.php?pid4612 Warm up Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 7206 Accepted Submission(s): 1681 Problem DescriptionN planets are …