溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

React5種非常流行的狀態(tài)管理庫是什么

發(fā)布時間:2021-10-26 13:57:06 來源:億速云 閱讀:116 作者:iii 欄目:web開發(fā)

本篇內(nèi)容主要講解“React 5種非常流行的狀態(tài)管理庫是什么”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“React 5種非常流行的狀態(tài)管理庫是什么”吧!

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

npx create-react-app react-state-examples  cd react-state-examples

無論何時何地,使用 start 命令啟動你的命令。

npm start

Recoil

Recoil Docs[6]

代碼行數(shù):30

我最喜歡 Recoil 的點是因為它基于 Hooks 的 API 以及它的直觀性。

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

Recoil 實踐

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

npm install recoil

接下來,將 RecoilRoot 添加到 App 程序的根/入口點:

import App from './App' import { RecoilRoot } from 'recoil'  export default function Main() {   return (     <RecoilRoot>       <App />     </RecoilRoot>   ); }

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

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

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

import React, { useState } from 'react'; import { RecoilRoot, atom, useRecoilState } from 'recoil';  const notesState = atom({   key: 'notesState', // unique ID (with respect to other atoms/selectors)   default: [], // default value (aka initial state) });  export default function Main() {   return (     <RecoilRoot>       <App />     </RecoilRoot>   ); }  function App() {   const [notes, setNotes] = useRecoilState(notesState);   const [input, setInput] = useState('')   function createNote() {     const notesArray = [...notes, input]     setNotes(notesArray)     setInput('')   }   return (     <div>       <h2>My notes app</h2>       <button onClick={createNote}>Create Note</button>       <input value={input} onChange={e => setInput(e.target.value)} />       { notes.map(note => <p key={note}>Note: {note}</p>) }     </div>   ); }

Recoil selectors

來自文檔

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

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

import { selector, useRecoilValue } from 'recoil'  const completedTodosState = selector({   key: 'todosState',   get: ({get}) => {     const todos = get(todosState)     return todos.filter(todo => todo.completed)   } })  const completedTodos = useRecoilValue(completedTodosState)

結(jié)論

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

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

Mobx

MobX React Lite Docs[7]

代碼行數(shù): 30

因為我在使用 Redux 之后使用了MobX React, 所以它一直是我最喜歡的管理 React  狀態(tài)庫之一。多年來,兩者之間的明顯差異,但是對我而言我不會改變我的選擇。

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

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

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

MobX 實踐

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

npm install mobx mobx-react-lite

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

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

import { makeAutoObservable } from 'mobx'  class NoteStore {   notes = []   createNote(note) {     this.notes = [...this.notes, note]   }   constructor() {     /* makes all data in store observable, replaces @observable */     makeAutoObservable(this)   } }  const Notes = new NoteStore()

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

import { observer } from 'mobx-react-lite' import { notes } from './NoteStore'  const App = observer(() => <h2>{notes[0]|| "No notes"}</h2>)

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

import React, { useState } from 'react' import { observer } from "mobx-react-lite" import { makeAutoObservable } from 'mobx'  class NoteStore {   notes = []   createNote(note) {     this.notes = [...this.notes, note]   }   constructor() {     makeAutoObservable(this)   } }  const Notes = new NoteStore()  const App = observer(() => {   const [input, setInput] = useState('')   const { notes } = Notes   function onCreateNote() {     Notes.createNote(input)     setInput('')   }   return (     <div>       <h2>My notes app</h2>       <button onClick={onCreateNote}>Create Note</button>       <input value={input} onChange={e => setInput(e.target.value)} />       { notes.map(note => <p key={note}>Note: {note}</p>) }     </div>   ) })  export default App

總結(jié)

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

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

XState

XState Docs[8]

代碼行數(shù):44

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

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

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

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

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

XState實踐

要開始使用XState,請安裝這些庫:

npm install xstate @xstate/react

要創(chuàng)建machine,請使用xstate中的Machine實用程序。這是我們將用于 Notes app 的machine:

import { Machine } from 'xstate'  const notesMachine = Machine({   id: 'notes',   initial: 'ready',   context: {     notes: [],     note: ''   },   states: {     ready: {},   },   on: {     "CHANGE": {       actions: [         assign({           note: (_, event) => event.value         })       ]     },     "CREATE_NOTE": {       actions: [         assign({           note: "",           notes: context => [...context.notes, context.note]         })       ]     }   } })

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

整個示例:

import React from 'react' import { useService } from '@xstate/react' import { Machine, assign, interpret } from 'xstate'  const notesMachine = Machine({   id: 'notes',   initial: 'ready',   context: {     notes: [],     note: ''   },   states: {     ready: {},   },   on: {     "CHANGE": {       actions: [         assign({           note: (_, event) => event.value         })       ]     },     "CREATE_NOTE": {       actions: [         assign({           note: "",           notes: context => [...context.notes, context.note]         })       ]     }   } })  const service = interpret(notesMachine).start()  export default function App() {   const [state, send] = useService(service)   const { context: { note, notes} } = state    return (     <div>       <h2>My notes app</h2>       <button onClick={() => send({ type: 'CREATE_NOTE' })}>Create Note</button>       <input value={note} onChange={e => send({ type: 'CHANGE', value: e.target.value})} />       { notes.map(note => <p key={note}>Note: {note}</p>) }     </div>   ) }

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

總結(jié)

XState 就像勞斯萊斯 或者說 狀態(tài)管理的瑞士軍刀??梢宰龊芏嗍虑?,但是所有功能都帶來額外的復(fù)雜性。

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

Redux

React Redux docs[13]

代碼行數(shù):33

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

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

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

Redux 實踐

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

npm install @reduxjs-toolkit react-redux

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

A store

Reducers

A provider

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

import React, { useState } from 'react' import { Provider, useDispatch, useSelector } from 'react-redux' import { configureStore, createReducer, combineReducers } from '@reduxjs/toolkit'  function App() {     const [input, setInput] = useState('')    /* useSelector 允許你檢索你想使用的狀態(tài),在我們的例子中是notes數(shù)組。 */   const notes = useSelector(state => state.notes)    /* dispatch 允許我們向 store 發(fā)送更新信息 */   const dispatch = useDispatch()    function onCreateNote() {     dispatch({ type: 'CREATE_NOTE', note: input })     setInput('')   }   return (     <div>       <h2>My notes app</h2>       <button onClick={onCreateNote}>Create Note</button>       <input value={input} onChange={e => setInput(e.target.value)} />       { notes.map(note => <p key={note}>Note: {note}</p>) }     </div>   ); }  /* 在這里,我們創(chuàng)建了一個 reducer,它將在`CREATE_NOTE`動作被觸發(fā)時更新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來創(chuàng)建store。 */     <Provider store={store}>       <App />     </Provider>   ) }  export default Main

總結(jié)

如果你正在尋找一個具有龐大社區(qū)、大量文檔以及大量問答的庫,那么Redux是一個非??孔V的選擇。因為它已誕生了很長時間,你只要在 Google  搜索,或多或少都能找到一些相關(guān)的答案。

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

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

Context

Context docs[14]

代碼行數(shù): 31

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

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

Context 實踐

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

/* 1. Import the context hooks */ import React, { useState, createContext, useContext } from 'react';  /* 2. Create a piece of context */ const NotesContext = createContext();  /* 3. Set the context using a provider */ <NotesContext.Provider value={{ notes: ['note1', 'note2'] }}>   <App /> </NotesContext.Provider>  /* 4. Use the context */ const { notes } = useContext(NotesContext);

全部代碼

import React, { useState, createContext, useContext } from 'react';  const NotesContext = createContext();  export default function Main() {   const [notes, setNotes] = useState([])   function createNote(note) {     const notesArray = [...notes, note]     setNotes(notesArray)   }   return (     <NotesContext.Provider value={{ notes, createNote }}>       <App />     </NotesContext.Provider>   ); }  function App() {   const { notes, createNote } = useContext(NotesContext);   const [input, setInput] = useState('')   function onCreateNote() {     createNote(input)     setInput('')   }    return (     <div>       <h2>My notes app</h2>       <button onClick={onCreateNote}>Create Note</button>       <input value={input} onChange={e => setInput(e.target.value)} />       { notes.map(note => <p key={note}>Note: {note}</p>) }     </div>   ); }

到此,相信大家對“React 5種非常流行的狀態(tài)管理庫是什么”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI