react钩子_迷上了钩子:如何使用React的useReducer()

react钩子

So the React Conference just happened and as always something new happened. Hooks happened! The React team talked about suspense, lazy loading, concurrent rendering, and hooks :D.

因此,React会议刚刚发生,并且一如既往地发生了一些新情况。 钩子发生了! React团队讨论了悬念,延迟加载,并发渲染和钩子 :D。

Now I’ll talk about my favorite hook useReducer and how you use it.

现在,我将讨论我最喜欢的钩子useReducer以及如何使用它。

In my PokemonInfo component, I have:

在我的PokemonInfo组件中,我有:

const [{ count, loading }, dispatch] = useReducer(reducer, initialState);

Which is equivalent to:

等效于:

const [state, dispatch] = useReducer(reducer, initialState);
const { count, loading } = state;

So what is const [state, dispatch] = useReducer(param1, param2) Let’s first talk about array destructuing which is happening below.

那么什么是const [state, dispatch] = useReducer(param1, param2)首先让我们谈谈数组解构 这正在发生在下面

const [state, dispatch] = useReducer(initialState);

Here’s an example of array destructing:

这是数组销毁的示例:

let myHeroes = ['Ant man', 'Batman']; // Mixing DC & Marvel :D
let [marvelHero, dcHero] = myHeroes; // destructuring array
/**
* myHeroes[0] == marvelHero => is 'Ant man'
* myHeroes[1] == dcHero => is 'Batman'
*/

So the method useReducer has two items in its array state and dispatch. Also the useReducer takes in two parameters: one is reducer the other is initial-state.

因此,方法useReducer的数组statedispatch有两个项目。 useReducer接受两个参数:一个是reducer ,另一个是initial-state

In the useReducer param reducer, I pass in:

useReducer参数reducer ,我传入:

const reducer = (state, action) => {switch (action.type) {case 'increment': {return { ...state, count: state.count + 1, loading: false };}case 'decrement': {return { ...state, count: state.count - 1, loading: false };}case 'loading': {return { ...state, loading: true };}default: {return state;}}
};

What this does is it takes in two arguments. One is the current state of the reducer and the other is the action. The action.type decides how it will update the reducer and return a new state to us.

这样做是有两个参数的。 一个是减速器的当前状态,另一个是动作。 action.type决定如何更新减速器并向我们返回新状态。

So if the action.type === increment

因此,如果action.type === increment

case 'increment': {      return { ...state, count: state.count + 1, loading: false };    
}

…it will return the state, which will have its count updated to +1 and loading set to false. Also where it says state.count + 1 here the state is actually the previous state.

…它将返回状态,该状态的计数将更新为+1并将加载设置为false 还在上面说state.count + 1地方,这里的state实际上是先前的状态。

In useReducer param initialState I pass in:

useReducer参数initialState我传入:

const initialState = {  loading: false,  count: 0
};

So if this is the initial state, the useReducer method returns two items from its array, state and dispatch. The state method is an object which has two keys count & loading that I destructure in my destructured array.

因此,如果这是初始状态,则useReducer方法从其数组中返回两项,即statedispatchstate方法是一个具有两个键count & loading的对象,我在已解构数组中对其进行了解构。

So I destructure an array, and inside the array, I destructure an object on the first index of the array like below.

因此,我解构了一个数组,然后在数组内部,对一个对象进行了解构,该对象位于数组的第一个索引上,如下所示。

const [{ count, loading }, dispatch] = useReducer(reducer, initialState);

Also I have a method called delay

我也有一种叫做delay的方法

// return true after 1500ms in time argument is passed to.
const delay = (time = 1500) => {  return new Promise(resolve => {    setTimeout(() => {      resolve(true);    }, time);  });
};

Now in my render method when I click the + button

现在在我的渲染方法中,当我单击+按钮时

<button type="button" onClick={onHandleIncrement}>+</button>

the onHandleIncrement function is executed, which does the following:

执行onHandleIncrement函数,该函数执行以下操作:

const onHandleIncrement = async () => {    dispatch({ type: 'loading' });    await delay(500);    dispatch({ type: 'increment' });  
};

It initially sets loading to true, adds a delay of 500ms and then increments the counter. Now I know this is not a real world case example, but it explains the point as to how a reducer works.

最初将loading设置为true,添加500ms的延迟,然后递增计数器。 现在,我知道这不是一个真实的案例,但是它解释了减速器如何工作的要点。

Last thing:

最后一件事:

<p>Count {loading ? 'loading..' : count}</p>

If loading is true, I show Count loading.. else I show Count {value}.

如果loading为true,则显示Count loading..否则显示Count {value}

This is how it looks in the UI:

这是它在UI中的外观:

I tried replicating Dan Abramov’s code that he showcased at the React Conference 2018. Here is the link to the code repository. Enjoy. :)

我尝试复制Dan Abramov在React Conference 2018上展示的代码。这是代码库的链接 请享用。 :)

Kindly do note that hooks are in an alpha version of React, and are in no way advised to be used in production. But there is a strong possibility that they will become a huge part of the eco-system in the future. So you should start playing around with react hooks now.
请注意,挂钩是React的alpha版本,绝不建议在生产中使用。 但是它们很可能在将来成为生态系统的重要组成部分。 因此,您现在应该开始使用react挂钩。

翻译自: https://www.freecodecamp.org/news/hooked-on-hooks-how-to-use-reacts-usereducer-2fe8f486b963/

react钩子

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392966.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

开发注意事项

明确需求 - 沟通 - 定好上下游接口 次序乱不得转载于:https://www.cnblogs.com/zslzz/p/6802437.html

c语言写桌面程序unity,Unity和iOS原生界面交互示例

注意上面的Main方法中出现的UnityAppController&#xff0c;该类就是作为控制类来实现Unity在iOS上显示的功能&#xff0c;在Main方法中就是将该控制器作为参数传递&#xff0c;即Main方法之后就会进入该类执行。所以这是我们进入到UnityAppController.mm&#xff0c;来查看该类…

oracle审计实施

1、语句审计 Audit session; Audit session By ; 与instance连接的每个会话生成一条审计记录。审计记录将在连接时期插入并且在断开连接时期进行更新。 保留有关会话的信息比如连接时期断开连接时期处理的逻辑和物理I/O&#xff0c;以及更多信息将存储在单独一条审计 记录中…

JPDA 架构研究5 - Agent利用环境指针访问VM (内存管理篇)

引入&#xff1a; 我们在前面说到JVMTI的客户端Agent,又提到Agent通过环境指针来访问VM。这里就来看看环境指针到底有多大的访问VM的能力。 分类1&#xff1a;内存管理 a.Allocate. 分配内存 jvmtiError Allocate(jvmtiEnv* env,jlong size,unsigned char** mem_ptr) size:分配…

leetcode94. 二叉树的中序遍历(dfs)

给定一个二叉树&#xff0c;返回它的中序 遍历。示例:输入: [1,null,2,3]1\2/3输出: [1,3,2]代码 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val x; }* }*/ class …

vtk删除一个actor_如何构建一个基于actor的简单区块链

vtk删除一个actorScalachain is a blockchain built using the Scala programming language and the actor model (Akka Framework).Scalachain是使用Scala编程语言和参与者模型( Akka Framework )构建的区块链。 In this story I will show the development process to build…

java枚举的简单介绍

1.枚举&#xff0c;enum关键字&#xff0c;相当于public final static. 2.举例&#xff1a; 首先定义了一个名为spiciness的枚举类型。 public enum Spiciness {NOT, MILD, MEDIUM, HOT, FLAMING } 再来测试一下enum&#xff0c;这个测试方法表明它有tostring()方法&#xff0…

浏览器中插入富文本编辑器

常用的富文本编辑器有CKEditor、UEEditor、TinyEditor、KindEditor等、以下以kindeditor编辑器的使用为例。 1.官网下载KindEditor编辑器http://kindeditor.net/down.php&#xff0c; 当前最新版本为4.1.11&#xff0c;解压缩后放入项目的static目录&#xff0c;作为js插件引用…

获取Extjs文本域中的内容

经常在Ext.select()和Ext.query()等问题上纠结&#xff0c;今天终于有了点新认识&#xff1a; 需求&#xff0c;假设我们的页面上有个panel ,其id为clusterstab_edit_details,这个panel的内部有个textarea,这个textarea的name为editDetails_Description,那么我们有多少方法可以…

android触摸指纹会触发按键功能,Android P新特性:利用触摸指纹识别器能阻止手机息屏...

设想你正在阅读手机上的文章&#xff0c;突然间显示屏变暗了一点。显然&#xff0c;你设置的30秒或1分钟超时息屏对于常规使用来说还可以&#xff0c;但对于阅读纯文本片段&#xff0c;还远远不够。因此&#xff0c;这时你会轻触屏幕&#xff0c;可能会上下滑动&#xff0c;以防…

leetcode37. 解数独(hashmap+回溯)

编写一个程序&#xff0c;通过已填充的空格来解决数独问题。 一个数独的解法需遵循如下规则&#xff1a; 数字 1-9 在每一行只能出现一次。 数字 1-9 在每一列只能出现一次。 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。 空白格用 ‘.’ 表示。 Note: 给定的数独序…

malloc、calloc、realloc和alloca各种的区别

需要先包含头文件 #include"malloc.h"malloc是标准的在堆中开辟新的空间比如char *pt(char *)malloc(10*sizeof(char));需要free(p)才会释放空间calloc也是开辟空间&#xff0c;但是使用方式不一样比如char *pt(char *)calloc(100, sizeof(char));然后用calloc开辟的…

如何对第一个Vue.js组件进行单元测试

by Sarah Dayan通过莎拉达扬 In Build Your First Vue.js Component we made a star rating component. We’ve covered many fundamental concepts to help you create more complex Vue.js components.在“ 构建您的第一个Vue.js组件”中&#xff0c;我们制作了星级评分组件…

Asp.NetCoreWebApi - RESTful Api

REST 常用http动词 WebApi 在 Asp.NetCore 中的实现3.1. 创建WebApi项目.3.2. 集成Entity Framework Core操作Mysql 3.2.1. 安装相关的包(为Xxxx.Infrastructure项目安装)3.2.2. 建立Entity和Context3.2.3. ConfigureService中注入EF服务3.2.4. 迁移数据库3.2.5. 数据库迁移结果…

android动画影子效果,Android TV常用动画的效果,View选中变大且有阴影(手机也能用)...

因为电视屏幕比较大&#xff0c;而我们看电视时距离电视有一定距离&#xff0c;这样就需要动画效果比较明显&#xff0c;这个动画就是应用最广泛的&#xff0c;因为很酷&#xff0c;呵呵&#xff0c;你懂得&#xff0c;看了就知道。效果如下图&#xff1a;public class MainAct…

leetcode226. 翻转二叉树(dfs)

翻转一棵二叉树。示例&#xff1a;输入&#xff1a;4/ \2 7/ \ / \ 1 3 6 9 输出&#xff1a;4/ \7 2/ \ / \ 9 6 3 1代码 /*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode righ…

Java BigDecimal Rounding Mode

UP        往绝对值大了取 DOWN      往绝对值小了取 CEILING     往值大了取 FLOOR      往值小了取 HALF_UP     不管正负&#xff0c;四舍五入 HALF_DOWN  不管正负&#xff0c;五舍六入 HALF_EVEN    整数部分为奇数&#xff1a;四舍五入…

如何成为一名有效的软件工程师

by Luis Santiago路易斯圣地亚哥(Luis Santiago) 如何成为一名有效的软件工程师 (How to become an effective software engineer) When I first started my journey as a software engineer I quickly noticed the great amount of cognitive load involved when working on …

linux 高可用----keepalived+lvs

什么是高可用&#xff1f; HA&#xff08;high availability&#xff09;即高可用性&#xff1b;就是在高可用集群中发生单点故障时&#xff0c;能够自动转移资源并切换服务&#xff0c;以保证服务一直在线的机制。 LVS LVS&#xff1a;&#xff08;linux virtual server&#…

用户配置相关文件

用户配置相关文件小总结 /etc/passwd 记录用户相关的信息 /etc/shadow 密码影子文件 /etc/group 记录用户组相关的信息 /etc/gshadow 密码影子文件&#xff08;组密码&#xff09; /etc/passwd 文件中各段的内容 第1段&#xff1a;用户名 第…