日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時(shí)間:8:30-17:00
你可能遇到了下面的問(wèn)題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營(yíng)銷解決方案
談?wù)凴eact5種非常流行的狀態(tài)管理庫(kù)

原文:sourl.cn/F95CrZ,代碼倉(cāng)庫(kù)地址: https://github.com/dabit3/react-state-5-ways

公司主營(yíng)業(yè)務(wù):成都做網(wǎng)站、成都網(wǎng)站制作、移動(dòng)網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實(shí)現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競(jìng)爭(zhēng)能力。成都創(chuàng)新互聯(lián)是一支青春激揚(yáng)、勤奮敬業(yè)、活力青春激揚(yáng)、勤奮敬業(yè)、活力澎湃、和諧高效的團(tuán)隊(duì)。公司秉承以“開放、自由、嚴(yán)謹(jǐn)、自律”為核心的企業(yè)文化,感謝他們對(duì)我們的高要求,感謝他們從不同領(lǐng)域給我們帶來(lái)的挑戰(zhàn),讓我們激情的團(tuán)隊(duì)有機(jī)會(huì)用頭腦與智慧不斷的給客戶帶來(lái)驚喜。成都創(chuàng)新互聯(lián)推出永清免費(fèi)做網(wǎng)站回饋大家。

在 React 中,似乎有無(wú)數(shù)種處理狀態(tài)管理的方法。想要了解各種庫(kù),去比較它們之間的如何選擇以及它們?nèi)绾卧鞫际且患钊祟^疼的事情。

當(dāng)我學(xué)習(xí)一些新東西時(shí),喜歡去比較那些實(shí)現(xiàn)相同功能的庫(kù),這有助于我理解各種庫(kù)之間的差別,并且能夠形成一個(gè)自己在構(gòu)建應(yīng)用的時(shí)候如何選擇使用它們的思維模型。

在本文中,我將一一介紹如何在 React App 中使用 5 種最流行的庫(kù)/APIS(使用最現(xiàn)代和最新版本的庫(kù))如何在 React App程序中使用全局狀態(tài)管理,并且達(dá)到一樣的效果。

  1. Recoil[1]
  2. MobX[2]
  3. XState[3]
  4. Redux (with hooks)[4]
  5. Context[5]

我還將試著解釋它們之間的差異,本文以 概述 - 代碼 - 結(jié)論的方式講解。

為了演示 APIS,我們將使用這些庫(kù)來(lái)做一個(gè)如何創(chuàng)建和展示筆記的應(yīng)用。

入門

如果你準(zhǔn)備好了,那么請(qǐng)先創(chuàng)建一個(gè)新的 React App,我們將使用它來(lái)開始我們的實(shí)踐:

 
 
 
 
  1. npx create-react-app react-state-examples 
  2.  
  3. cd react-state-examples 

無(wú)論何時(shí)何地,使用 start 命令啟動(dòng)你的命令。

 
 
 
 
  1. npm start 

Recoil

Recoil Docs[6]

代碼行數(shù):30

我最喜歡 Recoil 的點(diǎn)是因?yàn)樗?Hooks 的 API 以及它的直觀性。

與其他一些庫(kù)相比,我想說(shuō) Recoil 的和 API 比大多數(shù)庫(kù)更容易。

Recoil 實(shí)踐

開始使用Recoil前,先安裝依賴:

 
 
 
 
  1. npm install recoil 

接下來(lái),將 RecoilRoot 添加到 App 程序的根/入口點(diǎn):

 
 
 
 
  1. import App from './App' 
  2. import { RecoilRoot } from 'recoil' 
  3.  
  4. export default function Main() { 
  5.   return ( 
  6.      
  7.        
  8.      
  9.   ); 

下一步,要?jiǎng)?chuàng)建一些狀態(tài),我們將使用來(lái)自Recoil 的 atom 并設(shè)置key和一些初始狀態(tài):

 
 
 
 
  1. import { atom } from 'recoil' 
  2.  
  3. const notesState = atom({ 
  4.   key: 'notesState', // unique ID (with respect to other atoms/selectors) 
  5.   default: [], // default value (aka initial state) 
  6. }); 

現(xiàn)在,你可以在你app的任何位置使用來(lái)自 Recoil 的useRecoilState。這是使用 Recoil 實(shí)現(xiàn)的筆記 App:

 
 
 
 
  1. import React, { useState } from 'react'; 
  2. import { RecoilRoot, atom, useRecoilState } from 'recoil'; 
  3.  
  4. const notesState = atom({ 
  5.   key: 'notesState', // unique ID (with respect to other atoms/selectors) 
  6.   default: [], // default value (aka initial state) 
  7. }); 
  8.  
  9. export default function Main() { 
  10.   return ( 
  11.      
  12.        
  13.      
  14.   ); 
  15.  
  16. function App() { 
  17.   const [notes, setNotes] = useRecoilState(notesState); 
  18.   const [input, setInput] = useState('') 
  19.   function createNote() { 
  20.     const notesArray = [...notes, input] 
  21.     setNotes(notesArray) 
  22.     setInput('') 
  23.   } 
  24.   return ( 
  25.     
     
  26.       

    My notes app

     
  27.       Create Note 
  28.        setInput(e.target.value)} /> 
  29.       { notes.map(note => Note: {note}

    ) } 
  30.     
 
  •   ); 
  • Recoil selectors

    來(lái)自文檔

    selectors 用于計(jì)算基于 state 的派生屬性。這能讓我們避免冗余 state,通常無(wú)需使用 reducers 來(lái)保持狀態(tài)同步和有效。相反,最小狀態(tài)集存儲(chǔ)在 atoms 中。

    使用 Recoil selectors,你可以根據(jù) state 計(jì)算派生屬性,例如,可能是已過(guò)濾的待辦事項(xiàng)數(shù)組(在todo app 中)或已發(fā)貨的訂單數(shù)組(在電子商務(wù)應(yīng)用程序中):

     
     
     
     
    1. import { selector, useRecoilValue } from 'recoil' 
    2.  
    3. const completedTodosState = selector({ 
    4.   key: 'todosState', 
    5.   get: ({get}) => { 
    6.     const todos = get(todosState) 
    7.     return todos.filter(todo => todo.completed) 
    8.   } 
    9. }) 
    10.  
    11. const completedTodos = useRecoilValue(completedTodosState) 

    結(jié)論

    recoil 文檔說(shuō):"Recoil 是一個(gè)用于 React 狀態(tài)管理的實(shí)驗(yàn)性使用工具集。" 當(dāng)我決定在生產(chǎn)環(huán)境中使用庫(kù)時(shí),聽到"實(shí)驗(yàn)性"可能會(huì)非常擔(dān)心,所以至少在此刻,我不確定我現(xiàn)在對(duì)使用 Recoil 的感覺如何 。

    Recoil 很棒,我會(huì)為我的下一個(gè) app 使用上它,但是擔(dān)心實(shí)驗(yàn)性屬性,因此我將密切關(guān)注它,但現(xiàn)在不將它用于生產(chǎn)中。

    Mobx

    MobX React Lite Docs[7]

    代碼行數(shù): 30

    因?yàn)槲以谑褂?Redux 之后使用了MobX React, 所以它一直是我最喜歡的管理 React 狀態(tài)庫(kù)之一。多年來(lái),兩者之間的明顯差異,但是對(duì)我而言我不會(huì)改變我的選擇。

    MobX React 現(xiàn)在有一個(gè)輕量級(jí)版本(MobX React Lite),這個(gè)版本專門針對(duì)函數(shù)組件而誕生,它的有點(diǎn)是速度更快,更小。

    MobX 具有可觀察者和觀察者的概念,然而可觀察的API有所改變,那就是不必指定希望被觀察的每個(gè)項(xiàng),而是可以使用 makeAutoObservable 來(lái)為你處理所有事情。

    如果你希望數(shù)據(jù)是響應(yīng)的并且需要修改 store ,則可以用observer來(lái)包裝組件。

    MobX 實(shí)踐

    開始使用Mobx前,先安裝依賴:

     
     
     
     
    1. npm install mobx mobx-react-lite 

    該應(yīng)用的狀態(tài)已在 Store 中創(chuàng)建和管理。

    我們應(yīng)用的 store 如下所示:

     
     
     
     
    1. import { makeAutoObservable } from 'mobx' 
    2.  
    3. class NoteStore { 
    4.   notes = [] 
    5.   createNote(note) { 
    6.     this.notes = [...this.notes, note] 
    7.   } 
    8.   constructor() { 
    9.     /* makes all data in store observable, replaces @observable */ 
    10.     makeAutoObservable(this) 
    11.   } 
    12.  
    13. const Notes = new NoteStore() 

    然后,我們可以導(dǎo)入notes,并在 app 中的任何位置使用它們。要使組件是可觀察修改,需要將其包裝在observer中:

     
     
     
     
    1. import { observer } from 'mobx-react-lite' 
    2. import { notes } from './NoteStore' 
    3.  
    4. const App = observer(() => 

      {notes[0]|| "No notes"}

    讓我們看看它們?nèi)绾我黄疬\(yùn)行的:

     
     
     
     
    1. import React, { useState } from 'react' 
    2. import { observer } from "mobx-react-lite" 
    3. import { makeAutoObservable } from 'mobx' 
    4.  
    5. class NoteStore { 
    6.   notes = [] 
    7.   createNote(note) { 
    8.     this.notes = [...this.notes, note] 
    9.   } 
    10.   constructor() { 
    11.     makeAutoObservable(this) 
    12.   } 
    13.  
    14. const Notes = new NoteStore() 
    15.  
    16. const App = observer(() => { 
    17.   const [input, setInput] = useState('') 
    18.   const { notes } = Notes 
    19.   function onCreateNote() { 
    20.     Notes.createNote(input) 
    21.     setInput('') 
    22.   } 
    23.   return ( 
    24.     
       
    25.       

      My notes app

       
    26.       Create Note 
    27.        setInput(e.target.value)} /> 
    28.       { notes.map(note => Note: {note}

      ) } 
    29.     
     
  •   ) 
  • }) 
  •  
  • export default App 
  • 總結(jié)

    MobX 已經(jīng)誕生了一段時(shí)間,它很好用。與許多其他公司一樣,我在企業(yè)公司的大量線上應(yīng)用中使用了它。

    最近再次使用它之后的感受是,與其他一些庫(kù)相比,我覺得文檔略有不足。我會(huì)自己再嘗試一下,然后再做決定。

    XState

    XState Docs[8]

    代碼行數(shù):44

    XState 試圖解決現(xiàn)代UI復(fù)雜性的問(wèn)題,并且依賴于有限狀態(tài)機(jī)[9]的思想和實(shí)現(xiàn)。

    XState 是由 David Khourshid[10], 創(chuàng)建的,自發(fā)布以來(lái),我就看到過(guò)很多關(guān)于它的討論,所以我一直在觀望。這是在寫本文之前唯一不熟悉的庫(kù)。

    在使用之后,我可以肯定地說(shuō)它的實(shí)現(xiàn)方式是與其他庫(kù)截然不同的。它的復(fù)雜性比其他任何一種都要高,但是關(guān)于狀態(tài)如何工作的思維模型確實(shí)很 cool 而且對(duì)于提高能力很有幫助,在用它構(gòu)建一些 demo app 之后,讓我感到它很精妙。

    要了解有關(guān) XState 試圖解決的問(wèn)題的更多信息,請(qǐng)查看David Khourshid的這段視頻[11]或我也發(fā)現(xiàn)有趣的帖子[12]。

    XState 在這里的使用不是特別好,因?yàn)樗m合在更復(fù)雜的狀態(tài)下使用,但是這個(gè)簡(jiǎn)短的介紹至少可以希望為你提供一個(gè)選擇,以幫助你全面了解其工作原理。

    XState實(shí)踐

    要開始使用XState,請(qǐng)安裝這些庫(kù):

     
     
     
     
    1. npm install xstate @xstate/react 

    要?jiǎng)?chuàng)建machine,請(qǐng)使用xstate中的Machine實(shí)用程序。這是我們將用于 Notes app 的machine:

     
     
     
     
    1. import { Machine } from 'xstate' 
    2.  
    3. const notesMachine = Machine({ 
    4.   id: 'notes', 
    5.   initial: 'ready', 
    6.   context: { 
    7.     notes: [], 
    8.     note: '' 
    9.   }, 
    10.   states: { 
    11.     ready: {}, 
    12.   }, 
    13.   on: { 
    14.     "CHANGE": { 
    15.       actions: [ 
    16.         assign({ 
    17.           note: (_, event) => event.value 
    18.         }) 
    19.       ] 
    20.     }, 
    21.     "CREATE_NOTE": { 
    22.       actions: [ 
    23.         assign({ 
    24.           note: "", 
    25.           notes: context => [...context.notes, context.note] 
    26.         }) 
    27.       ] 
    28.     } 
    29.   } 
    30. }) 

    我們將使用的數(shù)據(jù)存儲(chǔ)在 context 中。在這里,我們有一個(gè) notes 列表 和一個(gè) input 輸入框。有兩種操作,一種用于創(chuàng)建 note(CREATE_NOTE),另一種用于設(shè)置 input(CHANGE)。

    整個(gè)示例:

     
     
     
     
    1. import React from 'react' 
    2. import { useService } from '@xstate/react' 
    3. import { Machine, assign, interpret } from 'xstate' 
    4.  
    5. const notesMachine = Machine({ 
    6.   id: 'notes', 
    7.   initial: 'ready', 
    8.   context: { 
    9.     notes: [], 
    10.     note: '' 
    11.   }, 
    12.   states: { 
    13.     ready: {}, 
    14.   }, 
    15.   on: { 
    16.     "CHANGE": { 
    17.       actions: [ 
    18.         assign({ 
    19.           note: (_, event) => event.value 
    20.         }) 
    21.       ] 
    22.     }, 
    23.     "CREATE_NOTE": { 
    24.       actions: [ 
    25.         assign({ 
    26.           note: "", 
    27.           notes: context => [...context.notes, context.note] 
    28.         }) 
    29.       ] 
    30.     } 
    31.   } 
    32. }) 
    33.  
    34. const service = interpret(notesMachine).start() 
    35.  
    36. export default function App() { 
    37.   const [state, send] = useService(service) 
    38.   const { context: { note, notes} } = state 
    39.  
    40.   return ( 
    41.     
       
    42.       

      My notes app

       
    43.        send({ type: 'CREATE_NOTE' })}>Create Note 
    44.        send({ type: 'CHANGE', value: e.target.value})} /> 
    45.       { notes.map(note => Note: {note}

      ) } 
    46.     
     
  •   ) 
  • 要在應(yīng)用中修改狀態(tài),我們使用 xstate-react 中的 useService hooks。

    總結(jié)

    XState 就像勞斯萊斯 或者說(shuō) 狀態(tài)管理的瑞士軍刀??梢宰龊芏嗍虑椋撬泄δ芏紟?lái)額外的復(fù)雜性。

    我希望將來(lái)能更好地學(xué)習(xí)和理解它,這樣我就可以將它應(yīng)用到 AWS 的相關(guān)問(wèn)題和參考它的架構(gòu),但是對(duì)于小型項(xiàng)目,我認(rèn)為這可能它太過(guò)龐大。

    Redux

    React Redux docs[13]

    代碼行數(shù):33

    Redux 是整個(gè) React 生態(tài)系統(tǒng)中最早,最成功的狀態(tài)管理庫(kù)之一。我已經(jīng)在許多項(xiàng)目中使用過(guò)Redux,如今它依然很強(qiáng)大。

    新的 Redux Hooks API 使 redux 使用起來(lái)不再那么麻煩,而且使用起來(lái)也更容易。

    Redux Toolkit 還改進(jìn)了 Redux,并大大降低了學(xué)習(xí)曲線。

    Redux 實(shí)踐

    開始使用Redux前,先安裝依賴:

     
     
     
     
    1. npm install @reduxjs-toolkit react-redux 

    要使用 Redux,您需要?jiǎng)?chuàng)建和配置以下內(nèi)容:

    A store

    Reducers

    A provider

    為了幫助解釋所有這些工作原理,我在實(shí)現(xiàn) Redux 中的 Notes app 的代碼中做了注釋:

     
     
     
     
    1. import React, { useState } from 'react' 
    2. import { Provider, useDispatch, useSelector } from 'react-redux' 
    3. import { configureStore, createReducer, combineReducers } from '@reduxjs/toolkit' 
    4.  
    5. function App() {   
    6.   const [input, setInput] = useState('') 
    7.  
    8.   /* useSelector 允許你檢索你想使用的狀態(tài),在我們的例子中是notes數(shù)組。 */ 
    9.   const notes = useSelector(state => state.notes) 
    10.  
    11.   /* dispatch 允許我們向 store 發(fā)送更新信息 */ 
    12.   const dispatch = useDispatch() 
    13.  
    14.   function onCreateNote() { 
    15.     dispatch({ type: 'CREATE_NOTE', note: input }) 
    16.     setInput('') 
    17.   } 
    18.   return ( 
    19.     
       
    20.       

      My notes app

       
    21.       Create Note 
    22.        setInput(e.target.value)} /> 
    23.       { notes.map(note => Note: {note}

      ) } 
    24.     
     
  •   ); 
  •  
  • /* 在這里,我們創(chuàng)建了一個(gè) reducer,它將在`CREATE_NOTE`動(dòng)作被觸發(fā)時(shí)更新note數(shù)組。 */ 
  • const notesReducer = createReducer([], { 
  •   'CREATE_NOTE': (state, action) => [...state, action.note] 
  • }) 
  •  
  • /* Here we create the store using the reducers in the app */ 
  • const reducers = combineReducers({ notes: notesReducer }) 
  • const store = configureStore({ reducer: reducers }) 
  •  
  • function Main() { 
  •   return ( 
  •     /* 在這里,我們使用app中的reducer來(lái)創(chuàng)建store。 */ 
  •      
  •        
  •      
  •   ) 
  •  
  • export default Main 
  • 總結(jié)

    如果你正在尋找一個(gè)具有龐大社區(qū)、大量文檔以及大量問(wèn)答的庫(kù),那么Redux是一個(gè)非??孔V的選擇。因?yàn)樗颜Q生了很長(zhǎng)時(shí)間,你只要在 Google 搜索,或多或少都能找到一些相關(guān)的答案。

    在使用異步操作(例如數(shù)據(jù)獲取)時(shí),通常需要添加其他中間件,這會(huì)增加它的成本和復(fù)雜性。

    對(duì)我來(lái)說(shuō),Redux 起初很難學(xué)習(xí)。一旦我熟悉了框架,就可以很容易地使用和理解它。過(guò)去,對(duì)于新開發(fā)人員而言,有時(shí)會(huì)感到不知所措,但是隨著 Redux Hooks 和 Redux Toolkit 的改進(jìn),學(xué)習(xí)過(guò)程變得容易得多,我仍然強(qiáng)烈建議 Redux 作為前置的選擇。

    Context

    Context docs[14]

    代碼行數(shù): 31

    context 的優(yōu)點(diǎn)在于,不需要安裝和依賴其他庫(kù),它是 React 的一部分。

    使用 context 非常簡(jiǎn)單,當(dāng)你嘗試管理大量不同的 context 值時(shí),問(wèn)題通常會(huì)出現(xiàn)在一些大或者復(fù)雜的應(yīng)用程序中,因此你通常必須構(gòu)建自己的抽象來(lái)自己管理這些情況。

    Context 實(shí)踐

    要?jiǎng)?chuàng)建和使用 context ,請(qǐng)直接從React導(dǎo)入鉤子。下面是它的工作原理:

     
     
     
     
    1. /* 1. Import the context hooks */ 
    2. import React, { useState, createContext, useContext } from 'react'; 
    3.  
    4. /* 2. Create a piece of context */ 
    5. const NotesContext = createContext(); 
    6.  
    7. /* 3. Set the context using a provider */ 
    8.  
    9.    
    10.  
    11.  
    12. /* 4. Use the context */ 
    13. const { notes } = useContext(NotesContext); 

    全部代碼

     
     
     
     
    1. import React, { useState, createContext, useContext } from 'react'; 
    2.  
    3. const NotesContext = createContext(); 
    4.  
    5. export default function Main() { 
    6.   const [notes, setNotes] = useState([]) 
    7.   function createNote(note) { 
    8.     const notesArray = [...notes, note] 
    9.     setNotes(notesArray) 
    10.   } 
    11.   return ( 
    12.      
    13.        
    14.      
    15.   ); 
    16.  
    17. function App() { 
    18.   const { notes, createNote } = useContext(NotesContext); 
    19.   const [input, setInput] = useState('') 
    20.   function onCreateNote() { 
    21.     createNote(input) 
    22.     setInput('') 
    23.   } 
    24.  
    25.   return ( 
    26.     
       
    27.       

      My notes app

       
    28.       Create Note 
    29.        setInput(e.target.value)} /> 
    30.       { notes.map(note => Note: {note}

      ) } 
    31.     
     
  •   ); 
  • 總結(jié)

    context 是一種管理 app 狀態(tài)的真正可靠且直接的方法。它的API可能不如其他一些庫(kù)那么好,但是如果你了解如何使用它,并且可以在你的 app 中使用它創(chuàng)建正確的數(shù)據(jù)抽象,那么選擇 context 來(lái)管理你的全局狀態(tài)就不會(huì)錯(cuò)。

    參考資料

    [1]Recoil: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#recoil

    [2]MobX: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#mobx

    [3]XState: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#xstate

    [4]Redux (with hooks): https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#redux

    [5]Context: https://dev.to/dabit3/react-state-6-ways-2bem?utm_source=digest_mailer&utm_medium=email&utm_campaign=digest_email#context

    [6]Recoil Docs: https://recoiljs.org/

    [7]MobX React Lite Docs: https://github.com/mobxjs/mobx-react-lite

    [8]XState Docs: https://xstate.js.org/docs/packages/xstate-react/

    [9]有限狀態(tài)機(jī): https://en.wikipedia.org/wiki/Finite-state_machine

    [10]David Khourshid: https://twitter.com/DavidKPiano

    [11]這段視頻: https://www.youtube.com/watch?v=RqTxtOXcv8Y

    [12]帖子: https://dev.to/hectorleiva/how-writing-state-machines-made-me-feel-like-a-programmer-2ndc

    [13]React Redux docs: https://react-redux.js.org/

    [14]Context docs: https://reactjs.org/docs/hooks-reference.html#usecontext

    本文轉(zhuǎn)載自微信公眾號(hào)「 秋風(fēng)的筆記」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系 秋風(fēng)的筆記公眾號(hào)。


    分享標(biāo)題:談?wù)凴eact5種非常流行的狀態(tài)管理庫(kù)
    本文來(lái)源:http://www.dlmjj.cn/article/cogihij.html