React使用Redux實(shí)現(xiàn)組件通信的項(xiàng)目實(shí)踐
在 React 項(xiàng)目中,父子組件通信通常依賴 props,兄弟組件通信則通過 狀態(tài)提升 或 Context。但是當(dāng)應(yīng)用逐漸復(fù)雜時(shí),這種方式會(huì)顯得繁瑣。此時(shí) Redux 就派上用場了 —— 它可以集中管理全局狀態(tài),任何組件都能方便地訂閱和修改狀態(tài)。
本文將帶你實(shí)現(xiàn)一個(gè)簡單的 計(jì)數(shù)器 demo,演示 Redux 在 React 中的組件通信。
一、環(huán)境準(zhǔn)備
安裝必要依賴:
npm install @reduxjs/toolkit react-redux
Redux Toolkit(RTK)是 Redux 官方推薦的寫法,簡化了很多冗余代碼。
二、目錄結(jié)構(gòu)
src/
store.ts
features/
counter/
counterSlice.ts
CounterA.tsx
CounterB.tsx
App.tsx
index.tsx
hooks.ts
這里我們會(huì)寫兩個(gè)兄弟組件:CounterA 和 CounterB,通過 Redux 實(shí)現(xiàn)通信。
三、配置 Redux Store
src/store.ts
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./features/counter/counterSlice";
export const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;
四、定義 Slice(狀態(tài)邏輯)
src/features/counter/counterSlice.ts
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { RootState } from "../../store";
interface CounterState {
value: number;
}
const initialState: CounterState = { value: 0 };
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
addBy: (state, action: PayloadAction<number>) => {
state.value += action.payload;
},
},
});
export const { increment, decrement, addBy } = counterSlice.actions;
export default counterSlice.reducer;
// 選擇器
export const selectCount = (state: RootState) => state.counter.value;
五、封裝 Typed Hooks(TS推薦)
src/hooks.ts
import { TypedUseSelectorHook, useDispatch, useSelector } from "react-redux";
import type { RootState, AppDispatch } from "./store";
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
六、兄弟組件通信示例
CounterA.tsx
import React from "react";
import { useAppDispatch } from "../../hooks";
import { increment, addBy } from "./counterSlice";
export default function CounterA() {
const dispatch = useAppDispatch();
return (
<div style={{ border: "1px solid #ccc", padding: 10, margin: 10 }}>
<h3>我是 CounterA</h3>
<button onClick={() => dispatch(increment())}>+1</button>
<button onClick={() => dispatch(addBy(5))}>+5</button>
</div>
);
}
CounterB.tsx
import React from "react";
import { useAppSelector } from "../../hooks";
import { selectCount } from "./counterSlice";
export default function CounterB() {
const count = useAppSelector(selectCount);
return (
<div style={{ border: "1px solid #ccc", padding: 10, margin: 10 }}>
<h3>我是 CounterB</h3>
<p>當(dāng)前計(jì)數(shù):{count}</p>
</div>
);
}
七、應(yīng)用入口
App.tsx
import React from "react";
import CounterA from "./features/counter/CounterA";
import CounterB from "./features/counter/CounterB";
export default function App() {
return (
<div style={{ padding: 20 }}>
<h2>Redux 通信 Demo</h2>
<CounterA />
<CounterB />
</div>
);
}
index.tsx
import React from "react";
import { createRoot } from "react-dom/client";
import { Provider } from "react-redux";
import { store } from "./store";
import App from "./App";
const root = createRoot(document.getElementById("root")!);
root.render(
<Provider store={store}>
<App />
</Provider>
);
八、運(yùn)行效果
- 點(diǎn)擊
CounterA中的 +1 或 +5 按鈕,會(huì)觸發(fā) Redux 的dispatch,修改全局狀態(tài)。 CounterB會(huì)實(shí)時(shí)響應(yīng),展示最新的計(jì)數(shù)值。
?? 這就實(shí)現(xiàn)了 兄弟組件通信,而且隨著應(yīng)用規(guī)模擴(kuò)大,你只需要在需要的地方使用 Redux,不再需要復(fù)雜的 props 傳遞。
九、總結(jié)
- 父子通信:直接用 props。
- 兄弟通信:Redux 是一種集中化管理方式,適合跨層級或復(fù)雜場景。
- Redux Toolkit 簡化了 reducer 和 action 的寫法,官方推薦。
- 在更大規(guī)模應(yīng)用中,還可以結(jié)合 Redux Persist(持久化存儲(chǔ))、RTK Query(數(shù)據(jù)請求管理)。
到此這篇關(guān)于React使用Redux實(shí)現(xiàn)組件通信的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)React Redux 組件通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
React Fiber 架構(gòu)解決頁面卡頓問題的全過程
本文從問題與目標(biāo)、核心數(shù)據(jù)結(jié)構(gòu)、調(diào)度與中斷、渲染階段與提交階段、優(yōu)先級與 lanes、并發(fā)特性到常見誤區(qū)與優(yōu)化建議,全景式拆解 React Fiber,為何它能夠顯著降低交互卡頓并提升可響應(yīng)性,感興趣的朋友跟隨小編一起看看吧2025-12-12
React Native 搭建開發(fā)環(huán)境的方法步驟
本篇文章主要介紹了React Native 搭建開發(fā)環(huán)境的方法步驟,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10
React 使用recharts實(shí)現(xiàn)散點(diǎn)地圖的示例代碼
這篇文章主要介紹了React 使用recharts實(shí)現(xiàn)散點(diǎn)地圖的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
react-draggable實(shí)現(xiàn)拖拽功能實(shí)例詳解
這篇文章主要給大家介紹了關(guān)于react-draggable實(shí)現(xiàn)拖拽功能的相關(guān)資料,React-Draggable一個(gè)使元素可拖動(dòng)的簡單組件,文中通過代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn)
本文主要介紹了react-redux action傳參及多個(gè)state處理的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
React?中使用?RxJS?優(yōu)化數(shù)據(jù)流的處理方案
這篇文章主要為大家介紹了React?中使用?RxJS?優(yōu)化數(shù)據(jù)流的處理方案示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-02-02

