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.pswp.cn/news/392966.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/392966.shtml
英文地址,請注明出處:http://en.pswp.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;用戶名 第…