Redux 被廣泛認為是專為 JavaScript 應用程式設計的強大狀態管理庫,通常與流行的框架 React 一起使用。透過提供可靠的狀態容器,Redux 建立了堅實的基礎,大大簡化了應用程式狀態的處理和故障排除任務。本指南深入研究了構成 Redux 的基本元件,提供了每個元素的詳細解釋,並說明了它們如何協同互通以簡化應用程式的整體功能。這次深入的探索旨在闡明 Redux 的內部工作原理,使開發人員能夠掌握這個狀態管理工具的複雜性,並在他們的專案中有效地利用其功能。
Redux 遵循單向資料流模型,並基於三個核心原則:
首先,安裝 Redux 和 React-Redux:
npm install redux react-redux @reduxjs/toolkit
此指令安裝核心 Redux 函式庫、Redux 的 React 綁定以及 Redux Toolkit,這簡化了許多常見任務,例如設定儲存和建立切片。
操作是將資料從應用程式傳送到 Redux 儲存的資訊負載。動作類型是表示動作的常數。
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 });
定義操作和操作類型顯然有助於保持一致性並減少應用程式中的錯誤。
Reducer 指定應用程式的狀態如何變更以回應傳送至儲存的操作。切片是應用程式單一功能的 Redux 減速機邏輯和操作的集合,使用 Redux Toolkit 的 createSlice 方法建立。
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;
要合併多切片:
import { combineReducers } from "@reduxjs/toolkit"; import counterReducer from "../slices/counterSlice"; const rootReducer = combineReducers({ counter: counterReducer, }); export default rootReducer;
store是將actions和reducers結合在一起的物件。它保存應用程式狀態,允許透過 getState() 存取它,透過dispatch(action) 更新它,並透過 subscribe(listener) 註冊監聽器。
import { configureStore } from "@reduxjs/toolkit"; import rootReducer from "../reducers/rootReducer"; const store = configureStore({ reducer: rootReducer, }); export default store;
要將 React 元件連接到 Redux 存儲,請使用 react-redux 中的 Provider 元件將儲存傳遞給您的元件,並使用 useSelector 和 useDispatch 鉤子來存取和操作狀態。
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 指南:用於 JavaScript 應用程式的強大狀態管理庫.png"; function App() { return ( <provider store="{store}"> <div classname="container mx-auto mt-24 text-center"> <img src="%7BMusCo%7D" alt="Redux 指南:用於 JavaScript 應用程式的強大狀態管理庫" 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">Coskuncelebi</span> </h5> </div> </div> </provider> ); } export default App;
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(); } 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;
Redux 是一個強大的函式庫,用於管理應用程式中的狀態。透過了解操作、減速器、儲存以及如何將所有內容連接到 React 元件,您可以建立可預測和可維護的應用程式。
更多信息,請查看 Redux 官方文檔:
透過遵循本指南,您應該對 Redux 有深入的了解,並能夠在自己的應用程式中實現它。
以上是Redux 指南:用於 JavaScript 應用程式的強大狀態管理庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!