偷偷摘套内射激情视频,久久精品99国产国产精,中文字幕无线乱码人妻,中文在线中文a,性爽19p

大家都說 Jotai 好,那就來個大PK!

開發(fā) 前端
今天就來看看主流 React 狀態(tài)管理庫的使用方式,看看哪個更合你意!

昨天發(fā)了一篇文章,分享了 Recoil 停止更新的情況,并推薦了當(dāng)前熱門的 React 狀態(tài)管理工具 Zustand。文章發(fā)布后,評論區(qū)不少同學(xué)表示 Jotai 在使用體驗上更勝一籌。鑒于此,今天就來看看主流 React 狀態(tài)管理庫的使用方式,看看哪個更合你意!

總覽

不得不承認(rèn),React 生態(tài)系統(tǒng)實在是太豐富了,僅狀態(tài)管理這一領(lǐng)域就提供了諸多選項,且持續(xù)有新工具涌現(xiàn)。當(dāng)前,React 狀態(tài)管理的主流庫包括 Redux、Zustand、MobX、Recoil、Jotai 等。其中,Redux 以遙遙領(lǐng)先的下載量獨占鰲頭,不過其增長速度有所放緩;而 Zustand 則緊隨其后,尤其在近兩年展現(xiàn)出迅猛的增長勢頭,成為不可忽視的力量。

Redux

特點

Redux 是一個老牌的全局狀態(tài)管理庫,它的核心思想如下:

  • 單一數(shù)據(jù)源:整個應(yīng)用的狀態(tài)被存儲在一個單一的對象樹中,即 store。這使得狀態(tài)的管理和調(diào)試變得更加簡單和直觀。
  • 狀態(tài)是只讀的:在 Redux 里,不能直接去修改 store 中的狀態(tài)。所有的狀態(tài)變更都必須通過觸發(fā)特定的動作(action)來發(fā)起請求。這種方式確保了狀態(tài)的變化是可追蹤的,避免了直接修改狀態(tài)帶來的問題。
  • 使用純函數(shù)來執(zhí)行修改:Reducer 是一個純函數(shù),它接受當(dāng)前狀態(tài)和一個 action 作為參數(shù),并返回新的狀態(tài)。Reducer 不會修改傳入的狀態(tài),而是返回一個新的狀態(tài)對象。這種設(shè)計使得狀態(tài)更新邏輯是可預(yù)測的,并且易于測試和維護(hù)。

基本使用

  1. 創(chuàng)建 Action(動作)
  • 定義: Action 是一個普通的 JavaScript 對象,用于描述應(yīng)用中發(fā)生了什么事情,也就是表明想要對狀態(tài)進(jìn)行何種改變。它就像是一個指令,告知 Redux 系統(tǒng)接下來需要執(zhí)行的操作任務(wù)。
  • 結(jié)構(gòu): 每個 Action 通常都包含一個必須的type屬性,其值為一個字符串,用于唯一標(biāo)識這個動作的類型,讓 Reducer 能夠根據(jù)這個類型來判斷該如何處理該動作。除此之外,還可以根據(jù)具體需求在 Action 對象中攜帶其他的數(shù)據(jù)(通常放在payload屬性中),這些數(shù)據(jù)就是執(zhí)行對應(yīng)操作所需要的具體信息。
// actions.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
  • 創(chuàng)建 Reducer: Reducer 是一個純函數(shù),它接收兩個參數(shù):當(dāng)前的整個狀態(tài)樹(作為第一個參數(shù))以及一個 Action(作為第二個參數(shù)),然后根據(jù) Action 的類型(通過type屬性來判斷)來決定如何更新狀態(tài),并返回一個新的狀態(tài)。
// reducer.js
import { INCREMENT, DECREMENT } from './actions';

const initialState = {
  count: 0
};

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case INCREMENT:
      return { ...state, count: state.count + 1 };
    case DECREMENT:
      return { ...state, count: state.count - 1 };
    default:
      return state;
  }
}

export default counterReducer;
  • 創(chuàng)建 Store(狀態(tài)容器):Store 是整個 Redux 架構(gòu)的核心,它把狀態(tài)(State)、Reducer 函數(shù)以及一些用于訂閱狀態(tài)變化的方法等都整合在一起,是整個應(yīng)用狀態(tài)的存儲中心和管理樞紐。創(chuàng)建 Store 時需要傳入一個根 Reducer:
// store.js
import { createStore } from 'redux';
import counterReducer from './reducer';

const store = createStore(counterReducer);

export default store;
  • 在 React 組件中使用 Redux:使用 Provider 組件將 store 提供給整個 React 應(yīng)用,并使用 useSelector 和 useDispatch 鉤子來訪問和更新狀態(tài):
// App.js
import React from 'react';
import { Provider, useSelector, useDispatch } from 'react-redux';
import store from './store';
import { increment, decrement } from './actions';

function Counter() {
  const count = useSelector((state) => state.count);
  const dispatch = useDispatch();

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => dispatch(increment())}>Increment</button>
      <button onClick={() => dispatch(decrement())}>Decrement</button>
    </div>
  );
}

function App() {
  return (
    <Provider store={store}>
      <Counter />
    </Provider>
  );
}

export default App;

缺點

  • 過于復(fù)雜: 對于小型項目或者簡單應(yīng)用來說,Redux 可能顯得過于復(fù)雜。它的概念(如 action、reducer、store)和工作流程需要一定的時間去理解和掌握。
  • 代碼冗余:Redux 需要編寫大量的模板代碼,包括定義 actions、reducers 和配置 store,這可能會增加開發(fā)的初始成本。
  • 異步處理復(fù)雜: Redux 默認(rèn)只支持同步處理,處理異步操作需要使用中間件,如 redux-thunk  redux-saga。這些中間件雖然強(qiáng)大,但增加了代碼的復(fù)雜性和學(xué)習(xí)成本。

Zustand

特點

Zustand 是一個輕量級狀態(tài)管理庫,專為 React 應(yīng)用設(shè)計。它提供了簡單直觀的 API,旨在減少樣板代碼,并且易于集成和使用。其特點如下:

  • 簡潔性:Zustand 的設(shè)計理念是保持極簡主義,通過簡單的 API 和最小化的配置來實現(xiàn)高效的狀態(tài)管理。
  • 基于 Hooks:它完全依賴于 React 的 Hooks 機(jī)制,允許開發(fā)者以聲明式的方式訂閱狀態(tài)變化并觸發(fā)更新。
  • 無特定立場:Zustand 不強(qiáng)制任何特定的設(shè)計模式或結(jié)構(gòu),給予開發(fā)者最大的靈活性。
  • 單一數(shù)據(jù)源:盡管 Zustand 支持多個獨立的 store,但每個 store 內(nèi)部仍然遵循單一數(shù)據(jù)源的原則,即所有狀態(tài)都集中存儲在一個地方。
  • 模塊化狀態(tài)切片:狀態(tài)可以被分割成不同的切片(slices),每個切片負(fù)責(zé)一部分應(yīng)用邏輯,便于管理和維護(hù)。
  • 異步支持:Zustand 可以輕松處理異步操作,允許在 store 中定義異步函數(shù)來執(zhí)行如 API 請求等任務(wù)。

基本使用

創(chuàng)建 Store:在 Zustand 中,Store是通過create函數(shù)創(chuàng)建的。每個Store都包含狀態(tài)和處理狀態(tài)的函數(shù)。

import { create } from 'zustand';

const useStore = create((set) => ({
  count: 0, // 初始狀態(tài)
  increment: () => set((state) => ({ count: state.count + 1 })), // 增加count的函數(shù)
  decrement: () => set((state) => ({ count: state.count - 1 })), // 減少count的函數(shù)
}));

create函數(shù)接受一個回調(diào)函數(shù),該回調(diào)函數(shù)接受一個set函數(shù)作為參數(shù),用于更新狀態(tài)。在這個回調(diào)函數(shù)中,定義了一個count狀態(tài)和兩個更新函數(shù)increment和decrement。

使用 Store:在組件中,可以使用自定義的 Hooks(上面的useStore)來獲取狀態(tài)和更新函數(shù),并在組件中使用它們。

import React from 'react';
import { useStore } from './store';

function Counter() {
  const { count, increment, decrement } = useStore();
  
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

訂閱特定狀態(tài)片段如果有一個包含多個狀態(tài)的store,但在組件中只需要訂閱其中一個狀態(tài),可以通過解構(gòu)賦值從useStore返回的完整狀態(tài)對象中提取需要的狀態(tài)。Zustand的智能選擇器功能允許這樣做,而不會導(dǎo)致不必要的重新渲染。

// store.js
import { create } from 'zustand';
 
const useStore = create((set) => ({
  count: 0,
  name: 'Zustand Store',
  increment: () => set((state) => ({ count: state.count + 1 })),
  setName: (newName) => set({ name: newName }),
}));
 
export default useStore;

在組件中,如果只想訂閱count狀態(tài),可以這樣做:

// MyComponent.js
import React from 'react';
import useStore from './store';

function MyComponent() {
  const { count } = useStore((state) => ({ count: state.count }));

  return (
    <div>
      <p>Count: {count}</p>
    </div>
  );
}

export default MyComponent;

Mobx

特點

MobX 是一個簡單、可擴(kuò)展的狀態(tài)管理庫。它通過透明的函數(shù)響應(yīng)式編程使得狀態(tài)管理變得簡單和高效。其核心思想如下:

  • 可觀察對象:MobX 通過 observable 裝飾器將數(shù)據(jù)標(biāo)記為可觀察的,當(dāng)這些數(shù)據(jù)發(fā)生變化時,依賴于這些數(shù)據(jù)的組件會自動更新。
  • 計算屬性:計算屬性是基于可觀察狀態(tài)的派生值,它們會自動更新以反映基礎(chǔ)狀態(tài)的變化。
  • 響應(yīng)式函數(shù):用于修改可觀察狀態(tài)的函數(shù),MobX 會自動追蹤這些函數(shù)中的狀態(tài)讀寫操作,并通知相關(guān)的觀察者進(jìn)行更新。
  • 自動依賴追蹤:MobX 會自動追蹤代碼中對可觀察狀態(tài)的訪問,建立起一個依賴關(guān)系圖,當(dāng)可觀察狀態(tài)發(fā)生變化時,會通知所有依賴于該狀態(tài)的觀察者進(jìn)行更新

基本使用

創(chuàng)建 Store: Store 是存儲應(yīng)用狀態(tài)的地方,并提供修改這些狀態(tài)的方法。MobX 提供了多種方式來定義可觀察的狀態(tài)和操作這些狀態(tài)的動作。

  • 使用 makeAutoObservabl:這是最推薦的方式,因為它避免了使用裝飾器(Babel 插件等),簡化了代碼。
import { makeAutoObservable } from 'mobx';

class CounterStore {
  count = 0;

  constructor() {
    makeAutoObservable(this);
  }

  increment = () => {
    this.count++;
  };

  decrement = () => {
    this.count--;
  };
}

// 創(chuàng)建全局 store 實例
const counterStore = new CounterStore();
export default counterStore;

在函數(shù)組件中使用 Store:對于函數(shù)組件,可以使用 useObserver Hook 來確保組件能夠響應(yīng)可觀察對象的變化。如果你需要在組件內(nèi)部創(chuàng)建局部的可觀察狀態(tài),則可以使用 useLocalStore。

  • 使用全局 Store (counterStore)
import React from 'react';
import { useObserver } from 'mobx-react';
import counterStore from './CounterStore';

const Counter = () => {
  return useObserver(() => (
    <div>
      <p>Count: {counterStore.count}</p>
      <button onClick={() => counterStore.increment()}>Increment</button>
      <button onClick={() => counterStore.decrement()}>Decrement</button>
    </div>
  ));
};

export default Counter;
  • 使用局部 Store (useLocalStore):如果需要創(chuàng)建局部可觀察狀態(tài),可以這樣做:
import React from 'react';
import { useObserver, useLocalStore } from 'mobx-react';

const Counter = () => {
  const store = useLocalStore(() => ({
    count: 0,
    increment: () => {
      this.count++;
    },
    decrement: () => {
      this.count--;
    }
  }));

  return useObserver(() => (
    <div>
      <p>Count: {store.count}</p>
      <button onClick={store.increment}>Increment</button>
      <button onClick={store.decrement}>Decrement</button>
    </div>
  ));
};

export default Counter;

注意:通常情況下,應(yīng)該盡量使用全局 store,除非有明確的理由需要局部狀態(tài)。

在類組件中使用 Store:對于類組件,可以使用 observer 高階組件(HOC)來將組件與 MobX 的狀態(tài)管理連接起來。observer 會自動檢測組件中使用的可觀察對象,并且當(dāng)這些對象發(fā)生變化時,會重新渲染組件。

import React from 'react';
import { observer } from 'mobx-react';
import counterStore from './CounterStore'; // 確保路徑正確

class Counter extends React.Component {
  handleIncrement = () => {
    counterStore.increment();
  };

  handleDecrement = () => {
    counterStore.decrement();
  };

  render() {
    return (
      <div>
        <p>Count: {counterStore.count}</p>
        <button onClick={this.handleIncrement}>Increment</button>
        <button onClick={this.handleDecrement}>Decrement</button>
      </div>
    );
  }
}

export default observer(Counter);

使用計算屬性和反應(yīng): 除了直接操作狀態(tài)外,MobX 還提供了 computed 和 reaction 等功能,用于基于現(xiàn)有狀態(tài)派生新值或監(jiān)聽狀態(tài)變化并執(zhí)行副作用。

  • 計算屬性 (computed)
import { makeAutoObservable, computed } from 'mobx';

class CounterStore {
  count = 0;

  constructor() {
    makeAutoObservable(this);
  }

  increment = () => {
    this.count++;
  };

  decrement = () => {
    this.count--;
  };

  @computed get doubleCount() {
    return this.count * 2;
  }
}

const counterStore = new CounterStore();
export default counterStore;
  • 反應(yīng) (reaction)
import { reaction } from 'mobx';

reaction(
  () => counterStore.count, // 跟蹤的依賴
  (count) => console.log(`Count changed to ${count}`) // 當(dāng)依賴變化時觸發(fā)的回調(diào)
);

Recoil

特點

Recoil 是由 Facebook 開發(fā)的一個用于 React 狀態(tài)管理庫,目前已停止維護(hù)。它旨在提供一種簡單、高效的方式來管理組件間共享的狀態(tài)。其核心思想如下:

  • 原子狀態(tài):Recoil 將狀態(tài)劃分為原子,每個原子是一個獨立的狀態(tài)片段,可以被任何 React 組件訪問和訂閱。
  • 選擇器:選擇器是基于原子狀態(tài)派生的狀態(tài),通過純函數(shù)來計算。它們可以同步或異步地轉(zhuǎn)換狀態(tài)。類似于 Redux 中的 reducer 或 MobX 中的 computed 屬性。
  • 細(xì)粒度依賴跟蹤:Recoil 內(nèi)置了高效的依賴跟蹤機(jī)制,只有當(dāng)組件實際依賴的狀態(tài)發(fā)生變化時才會觸發(fā)重新渲染。
  • 單向數(shù)據(jù)流與響應(yīng)式更新Recoil 遵循單向數(shù)據(jù)流原則,組件通過訂閱原子或選擇器來獲取狀態(tài),當(dāng)有事件觸發(fā)狀態(tài)更新時,狀態(tài)的變化會沿著數(shù)據(jù)流從原子、選擇器流向訂閱它們的組件,觸發(fā)組件重新渲染,從而更新 UI。

基本使用

創(chuàng)建 Atom 和 Selector:

  • 原子創(chuàng)建: 定義一個 atom 來表示應(yīng)用中的某個狀態(tài)片段。
import { atom } from 'recoil';

export const counterState = atom({
  key: 'counterState',
  default: 0,
});
  • 創(chuàng)建 Selector:定義一個 selector 來計算派生狀態(tài)或執(zhí)行異步操作。
import { selector } from 'recoil';
import { counterState } from './atoms';

export const doubleCounterSelector = selector({
  key: 'doubleCounterSelector',
  get: ({ get }) => {
    const count = get(counterState);
    return count * 2;
  },
});

使用 Atom 和 Selector

  • 在組件中使用 useRecoilState Hook 來獲取原子狀態(tài)并更新(適用于讀寫原子狀態(tài)的場景)。
import React from 'react';
import { useRecoilState } from 'recoil';
import { counterState } from './atoms';

const Counter = () => {
  const [count, setCount] = useRecoilState(counterState);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
      <button onClick={() => setCount(count - 1)}>Decrement</button>
    </div>
  );
};

export default Counter;
  • 在組件中使用 useRecoilValue Hook 僅獲取原子或選擇器的值(適用于只讀場景):
import React from 'react';
import { useRecoilValue } from 'recoil';
import { doubleCounterSelector } from './selectors';

const DoubleCounter = () => {
  const doubleCount = useRecoilValue(doubleCounterSelector);

  return <p>Double Count: {doubleCount}</p>;
};

export default DoubleCounter;
  • 使用 useSetRecoilState Hook 僅獲取更新原子狀態(tài)的函數(shù)(適用于只寫場景):
import React from 'react';
import { useSetRecoilState } from'recoil';
import { countAtom } from './atoms';

const IncrementButtonComponent = () => {
    const setCount = useSetRecoilState(countAtom);
    return (
        <button onClick={() => setCount((prevCount) => prevCount + 1)}>Increment</button>
    );
};

Jotai

特點

Jotai 是一個輕量級且靈活的 React 狀態(tài)管理庫,采用原子化狀態(tài)管理模型。它受到了 Recoil 的啟發(fā),旨在提供一種簡單而直觀的方式來管理 React 中的狀態(tài)。其核心思想:

  • 原子化狀態(tài)管理:Jotai 使用原子作為狀態(tài)的基本單位。每個原子代表一個獨立的狀態(tài)片段,可以被多個組件共享和訪問。
  • 組合性:通過組合 atoms 和選擇器,可以構(gòu)建復(fù)雜的、依賴于其他狀態(tài)的狀態(tài)邏輯。這種組合性使得狀態(tài)管理更加模塊化和靈活。
  • 細(xì)粒度依賴跟蹤:Jotai 內(nèi)置了高效的依賴跟蹤機(jī)制,只有當(dāng)組件實際依賴的狀態(tài)發(fā)生變化時才會觸發(fā)重新渲染。

基本使用

創(chuàng)建 Atom

  • 簡單原子創(chuàng)建:定義一個 atom 來表示應(yīng)用中的某個狀態(tài)片段。
import { atom } from 'jotai';

export const countAtom = atom(0);
  • 派生原子創(chuàng)建(基于已有原子進(jìn)行計算等)
import { atom } from 'jotai';
import { countAtom } from './atoms';

export const doubleCountAtom = atom((get) => get(countAtom) * 2);

使用 Atom

  • 使用 useAtom Hook 獲取和更新原子狀態(tài)(適用于讀寫原子狀態(tài)場景):
import React from 'react';
import { useAtom } from 'jotai';
import { countAtom } from './atoms';

const Counter = () => {
  const [count, setCount] = useAtom(countAtom);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
      <button onClick={() => setCount((prev) => prev - 1)}>Decrement</button>
    </div>
  );
};

export default Counter;
  • 使用 useAtomValue Hook 僅獲取原子狀態(tài)(適用于只讀場景):
import React from 'react';
import { useAtomValue } from 'jotai';
import { doubleCountAtom } from './derivedAtoms';

const DoubleCounter = () => {
  const doubleCount = useAtomValue(doubleCountAtom);

  return <p>Double Count: {doubleCount}</p>;
};

export default DoubleCounter;
  • 使用 useSetAtom Hook 僅獲取更新原子狀態(tài)的函數(shù)(適用于只寫場景):
import React from 'react';
import { useAtomValue } from 'jotai';
import { countAtom } from './derivedAtoms';

const IncrementButtonComponent = () => {
    const setCount = useSetAtom(countAtom);
    return (
        <button onClick={() => setCount((prevCount) => prevCount + 1)}>Increment</button>
    );
};
責(zé)任編輯:姜華 來源: 前端充電寶
相關(guān)推薦

2020-09-04 07:33:12

Redis HashMap 數(shù)據(jù)

2015-11-27 10:02:05

WindowsLinuxLabxNow

2012-11-19 10:09:25

2022-05-17 20:37:41

MyPick泛型對象類型

2020-07-06 08:15:59

SQLSELECT優(yōu)化

2020-03-02 19:08:21

JVMJDKJRE

2015-07-27 10:34:55

大數(shù)據(jù)大忽悠

2019-11-06 19:21:07

Pythonargparse解釋器

2022-03-23 08:01:04

Python語言代碼

2024-09-29 08:57:25

2023-09-26 11:59:48

ChatGPT人工智能

2023-02-03 15:21:52

2015-11-23 16:41:20

EC

2022-01-27 11:02:04

索引數(shù)據(jù)存儲

2023-04-28 12:01:56

Spring項目編譯

2021-06-22 10:14:44

Kubernetes容器運維

2021-05-08 13:26:30

IDP首席信息官內(nèi)部開發(fā)者平臺

2022-05-09 11:01:18

配置文件數(shù)據(jù)庫

2023-04-26 08:19:48

Nacos高可用開發(fā)
點贊
收藏

51CTO技術(shù)棧公眾號