ホームページ  >  記事  >  ウェブフロントエンド  >  マスター Redux: React 開発者のための簡単なガイド

マスター Redux: React 開発者のための簡単なガイド

王林
王林オリジナル
2024-07-20 16:33:02290ブラウズ

Master Redux: A Simple Guide for React Developers

Redux は、JavaScript アプリケーション専用に設計された堅牢な状態管理ライブラリとして広く認識されており、人気のフレームワーク React と連携してよく利用されます。 Redux は、信頼できる状態コンテナを提供することで、アプリケーション状態の処理とトラブルシューティングのタスクを大幅に簡素化する強固な基盤を確立します。このガイドでは、Redux を構成する基本コンポーネントを深く掘り下げ、各要素の詳細な説明を提供し、それらがどのように相乗的に相互運用してアプリケーションの全体的な機能を合理化するかを示します。この詳細な調査の目的は、Redux の内部動作を解明し、開発者がこの状態管理ツールの複雑さを把握し、その機能をプロジェクトで効果的に活用できるようにすることです。

目次

  • Redux の概要

  • React アプリケーションでの Redux のセットアップ

  • アクションとアクションのタイプ

  • レデ​​ューサーとスライス

  • ストアの構成

  • React コンポーネントの接続

  • 結論と参考文献

1. Redux の概要

Redux は一方向のデータ フロー モデルに従い、次の 3 つの基本原則に基づいています。

信頼できる唯一の情報源: アプリケーション全体の状態は、単一ストア内のオブジェクト ツリーに保存されます。この一元化により、アプリケーション全体のデバッグと変更の追跡が容易になります。

状態は読み取り専用です: 状態を変更する唯一の方法は、何が起こったかを説明するオブジェクトであるアクションを発行することです。これにより、状態の突然変異が予測可能で追跡可能になります。

変更は純粋関数で行われます。アクションによって状態ツリーがどのように変換されるかを指定するには、純粋なリデューサーを作成します。純粋な関数は予測可能でテスト可能であるため、デバッグと単体テストが簡素化されます。

2. React アプリケーションでの Redux のセットアップ

まず、Redux と React-Redux をインストールします。

npm install redux 反応-redux @reduxjs/toolkit

このコマンドは、コア Redux ライブラリ、Redux 用の React バインディング、Redux ツールキットをインストールします。これにより、ストアのセットアップやスライスの作成などの多くの一般的なタスクが簡素化されます。

3. アクションとアクションの種類

アクションは、アプリケーションから Redux ストアにデータを送信する情報のペイロードです。アクション タイプは、アクションを表す定数です。

actionTypes.js

export const INCREMENT = "INCREMENT";
export const DECREMENT = "DECREMENT";
export const INCREMENT_BY_VALUE = "INCREMENT_BY_VALUE";
export const RESET = "RESET";

export const increment = () => ({ type: INCREMENT });
export const decrement = () => ({ type: DECREMENT });
export const incrementByValue = (value) => ({
  type: INCREMENT_BY_VALUE,
  payload: value,
});
export const reset = () => ({ type: RESET });

アクションとアクション タイプを定義すると、一貫性を維持し、アプリケーション内のエラーを減らすのに明らかに役立ちます。

4. レデューサとスライス

Reducer は、ストアに送信されたアクションに応じてアプリケーションの状態がどのように変化するかを指定します。スライスは、アプリの 1 つの機能に対する Redux リデューサー ロジックとアクションのコレクションであり、Redux Toolkit の createSlice メソッドを使用して作成されます。

counterSlice.js

import { createSlice } from "@reduxjs/toolkit";
const initialState = { number: 0 };
const counterSlice = createSlice({
  name: "counter",
  initialState,
  reducers: {
    increment: (state) => {
      state.number += 5;
    },
    decrement: (state) => {
      state.number = Math.max(0, state.number - 5);
    },
    incrementByValue: (state, action) => {
      state.number += action.payload;
    },
    reset: (state) => {
      state.number = 0;
    },
  },
});

export const { increment, decrement, incrementByValue, reset 
    } = counterSlice.actions;
export default counterSlice.reducer;

rootReducer.js

複数のスライスを結合するには:

import { combineReducers 
    } from "@reduxjs/toolkit";
import counterReducer from "../slices/counterSlice";

const rootReducer = combineReducers({
  counter: counterReducer,
});

export default rootReducer;

5. ストアの構成

ストアは、アクションとリデューサーを結び付けるオブジェクトです。アプリケーションの状態を保持し、getState() を介してアクセスを許可し、dispatch(action) を介して更新し、subscribe(listener) を介してリスナーを登録します。

store.js

import { configureStore 
    } from "@reduxjs/toolkit";
import rootReducer from "../reducers/rootReducer";

const store = configureStore({
  reducer: rootReducer,
});

export default store;

6. React コンポーネントの接続

React コンポーネントを Redux ストアに接続するには、react-redux の Provider コンポーネントを使用してストアをコンポーネントに渡し、useSelector フックと useDispatch フックを使用して状態にアクセスして操作します。

App.js

import React from "react";
import { Provider } from "react-redux";
import store from "./redux/store/store";
import Counter from "./components/Counter";
import MusCo from "./MusCo redux マスター Redux: React 開発者のための簡単なガイド.png";

function App() {
  return (
    <provider store="{store}">
      <div classname="container mx-auto mt-24 text-center">
        <img src="%7BMusCo%7D" alt="マスター Redux: React 開発者のための簡単なガイド" classname="w-40 mx-auto mt-24 rounded-full">
        <h1 classname="container m-auto text-2xl 
            font-semibold text-center text-violet-700">
          Practice Redux with 
            <span classname="font-extrabold 
            text-violet-900">MusCo</span>
        </h1>
        <div classname="relative inline-block mt-8 text-sm">
          <counter></counter>
          <h5 classname="absolute bottom-0 right-0 mb-2 
                mr-2 font-semibold text-violet-700">
            <span classname="italic font-normal">by</span> 
            <span classname="font-semibold text-violet-900">Mus</span>tafa <span classname="font-semibold 
                text-violet-900">Co</span>skuncelebi
          </h5>
        </div>
      </div>
    </provider>
  );
}

export default App;

CounterComponent.js

import { useDispatch, useSelector } from "react-redux";
import {
  decrement,
  increment,
  incrementByValue,
  reset,
} from "../slices/counterSlice";
import { useState, useEffect } from "react";

function Counter() {
  const [value, setValue] = useState("");
  const dispatch = useDispatch();
  const number = useSelector((state) => state.counter.number);

  useEffect(() => {
    const showcase = document.querySelector("#showcase");
    if (number 
      <h1 classname="mb-3 text-3xl font-bold mt-7 
        text-violet-700">Counter</h1>
      <p classname="text-5xl text-violet-900">{number}</p>
      <div classname="flex mx-8 space-x-5" style="{{" justifycontent:>
        <button onclick="{()"> dispatch(increment())} 
            className="w-40 h-10 p-2 mt-5 rounded-md outline-1 
            outline-violet-500 outline text-violet-900" 
            style={{ backgroundColor: "#c2ff72" }}>
          Increment by 5
        </button>
        <button onclick="{()"> dispatch(decrement())} 
            className="w-40 h-10 p-2 mt-5 rounded-md outline-1 
            outline-violet-500 outline text-violet-900" 
            style={number 
          Decrement by 5
        </button>
      </div>
      <div classname="flex mx-8 mt-5 space-x-3 mb-7" style="{{" justifycontent: alignitems:>
        <div classname="p-5 space-x-5 rounded-md outline 
            outline-1 outline-violet-500">
          <input classname="w-40 h-10 pl-2 rounded-md outline 
                outline-1 outline-violet-500 text-violet-900" onchange="{(e)"> {
            let newValue = e.target.value.trim();
            if (newValue === "") {
              newValue = "";
              reset();
            }
            // Check the trimmed value consists only of digits
            if (/^\d*$/.test(newValue)) {
              setValue(newValue);
            }
          }} value={value} placeholder="Enter Value" />
          <button onclick="{()"> {
            dispatch(incrementByValue(Number(value)));
            setValue("");
          }} className="w-40 h-10 p-2 rounded-md outline-1 
                outline-violet-500 outline text-violet-900" 
                style={{ backgroundColor: "#c2ff72" }}>
            Add this Value
          </button>
        </div>
      </div>
      <button onclick="{()"> {
        dispatch(reset());
        setValue("");
      }} className="w-20 h-10 p-2 text-white rounded-md outline-1 
            outline-violet-500 outline mb-7 bg-violet-900">
        Reset
      </button>
      <h3 classname="text-violet-400" id="showcase" style="{{" visibility: marginbottom:>
        Counter cannot be less than 0
      </h3>
    
  );
}

export default Counter;

7. 結論と参考文献

Redux は、アプリケーションの状態を管理するための強力なライブラリです。アクション、リデューサー、ストア、およびすべてを React コンポーネントに接続する方法を理解することで、予測可能で保守可能なアプリケーションを作成できます。

キーポイント:

アクション: アプリ内で何が起こるかを定義します。

リデューサー: アクションに応じて状態がどのように変化するかを指定します。

ストア: 状態を保持し、アクションを処理します。

プロバイダ: ストアを React コンポーネントに渡します。

プロジェクト ファイル:

ここから、私の GitHub リポジトリに保存されているプロジェクト ファイルにアクセスできます。
redux-counter

詳細については、Redux の公式ドキュメントを参照してください。

Redux ドキュメント

Redux ツールキットのドキュメント

React-Redux ドキュメント

このガイドに従うことで、Redux をしっかりと理解し、独自のアプリケーションに実装できるようになります。

コーディングを楽しんでください!

ハッシュノードとメディアで公開されました

以上がマスター Redux: React 開発者のための簡単なガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。