React?中使用?Redux?Toolkit?狀態(tài)管理的實踐
Redux的核心概念
Redux的核心概念包括Store、Action、Reducer、State和Dispatch。
- State 是 Redux Store 中的數(shù)據(jù)結(jié)構(gòu),代表應(yīng)用的整個狀態(tài)。在 Redux 中,State 是只讀的,任何更新 State 的操作都必須通過 Reducer 來完成,確保狀態(tài)的不可變性。
- Action 是一種描述應(yīng)用中發(fā)生了什么的 JavaScript 對象。每個 Action 通常包含一個 type 屬性,用于指明 Action 的類型,此外還可以包含其他有用的屬性(如 payload),以提供更詳細的信息。Action 通常通過 createAction 函數(shù)或 dispatch 方法生成。
- Reducer 是 Redux 的核心部分。它是一個純函數(shù),接收當(dāng)前的狀態(tài)(state)和一個 Action,并返回一個新的狀態(tài)。Reducer 不會直接修改傳入的 state,而是基于當(dāng)前狀態(tài)和 Action 創(chuàng)建并返回一個新的狀態(tài)。
- Dispatch 是一種方法,用于將 Action 分發(fā)給 Reducer。每當(dāng)你想要修改應(yīng)用的狀態(tài)時,都需要通過 Dispatch 來觸發(fā) Action,從而引發(fā)狀態(tài)的更新。
在現(xiàn)代 React 應(yīng)用程序中,狀態(tài)管理是一個至關(guān)重要的部分。使用 Redux Toolkit 可以簡化 Redux 的配置和管理。本文將通過三個文件的示例,詳細講解如何使用 Redux Toolkit 創(chuàng)建和管理一個簡單的計數(shù)器狀態(tài),并通過類比源 store 和根 store 的概念,加以更好地理解。
一、什么是源 Store 和根 Store?
這里只是自己覺得這樣定義會更好理解一些,實際并沒有這樣的概念
源 Store
源 store 是模塊化的狀態(tài)管理單元,負責(zé)特定功能的狀態(tài)和操作。使用 createSlice 創(chuàng)建的 slice 就是源 store。
類比:可以想象成一個專注于特定產(chǎn)品的車間,例如一個玩具制造車間。它只負責(zé)制造特定類型的玩具(如計數(shù)器的狀態(tài)管理),并且有自己的一套操作流程(增、減、重置)。
根 Store
根 store 是整個應(yīng)用的狀態(tài)管理中心,使用 configureStore 組合多個源 store。它負責(zé)將所有的狀態(tài)和邏輯集中起來,提供給整個應(yīng)用使用。
類比:可以想象成一個大型工廠,里面有多個車間(源 store)。有負責(zé)制造玩具的,有負責(zé)制造家具的。。。這個工廠負責(zé)管理和協(xié)調(diào)各個車間的生產(chǎn),并且能夠根據(jù)需求調(diào)整生產(chǎn)線(即添加或修改源 store)。

二、創(chuàng)建 Counter Store
2.1 定義源 Store
在一個新的文件 counterSlice.js 中,我們將創(chuàng)建計數(shù)器的 slice:
// store/modules/xxx.js
import { createSlice } from '@reduxjs/toolkit';
// 創(chuàng)建一個 slice
const counterSlice = createSlice({
name: 'counter', // 定義 slice 的名稱
initialState: { // 初始化狀態(tài)
count: 0, // 需要被全局維護的數(shù)據(jù)
},
reducers: { // 定義修改狀態(tài)的方法
increment(state) {
state.count += 1; // 增加計數(shù)
},
decrement(state) {
state.count -= 1; // 減少計數(shù)
},
reset(state) {
state.count = 0; // 重置計數(shù)
},
},
});
// 導(dǎo)出 action 對象
export const { increment, decrement, reset } = counterSlice.actions;
// 導(dǎo)出 reducer 函數(shù)
export const counterReducer = counterSlice.reducer;
在這個例子中,counterSlice 就是我們的源 store,它初始化了一個 count 狀態(tài),并提供了三個 reducers 來修改這個狀態(tài)。
三、組合 Store(根)
在另一個文件 store.js 中,我們將使用 configureStore 來組合根 store,并把 counterReducer 傳入:
// store/index.js
import { configureStore } from '@reduxjs/toolkit';
import { counterReducer } from './counterSlice';
// 創(chuàng)建根 store
const store = configureStore({
reducer: {
counter: counterReducer, // 將源 reducer 組合到根 store 中
},
});
export default store;
這里,store 就是我們的根 store,它可以容納多個源 store(在本例中只有 counter),并將它們組合在一起進行集中管理。
根store中可以定義多個源store,這里只示例一個
四、連接 React 和 Redux
我們目前只是使用了源store中的reducer函數(shù)來組合根store,還有定義導(dǎo)出的源store中的action對象并沒有使用
現(xiàn)在我們已經(jīng)定義了 store,但還需要將其鏈接到我們的 React 應(yīng)用中。我們將使用 react-redux 中的 Provider 組件來實現(xiàn)這一點。
4.1 綁定 Store(為組件注入store)
在 index.js 或 App.js 中,我們將 Provider 組件包裹住我們的應(yīng)用:
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
4.2 使用 Store 中的數(shù)據(jù)(調(diào)用觸發(fā))
在我們的組件中,使用 useSelector 鉤子來訪問 store 中的狀態(tài),并使用 useDispatch 鉤子來觸發(fā) action。
// App.js
import React from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, reset } from './counterSlice';
const Counter = () => {
const count = useSelector(state => state.counter.count); // 獲取狀態(tài)
const dispatch = useDispatch(); // 獲取 dispatch 函數(shù)
return (
<div>
<h1>Count: {count}</h1>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
<button onClick={() => dispatch(reset())}>Reset</button>
</div>
);
};
export default Counter;
在這個組件中,我們通過 useSelector 獲取 count 狀態(tài),并通過 useDispatch 觸發(fā) increment、decrement 和 reset 這三個 action。
總結(jié)
通過以上步驟,我們成功使用 Redux Toolkit 創(chuàng)建了一個簡單的計數(shù)器應(yīng)用。整個過程包括:
- 定義源 store(創(chuàng)建 slice)。
- 將源 store 組合到根 store 中。
- 通過
Provider注入 store 到 React 應(yīng)用中。 - 使用
useSelector和useDispatch連接組件與 store,實現(xiàn)狀態(tài)管理。
擴展:
1.action傳參:
- 對源store的reducer中的action對象多傳遞一個action參數(shù),這個參數(shù)就是我們觸發(fā)方法傳遞的數(shù)據(jù)了
- 通過action.payload拿到數(shù)據(jù)
addToNum(state, action) {
state.count = action.payload
}調(diào)用觸發(fā)
dispatch(addToNum(20))
2.異步操作獲取數(shù)據(jù)
(1).在源store外面定義一個異步函數(shù)并暴露出去,異步函數(shù)中調(diào)用dispatch()
dispatch中傳遞源store中reducer中的action對象
// channelStore.js (源)
// 解構(gòu)出action對象
const {setChannel} = channelStore.actions
// 封裝函數(shù)
const fetchChannelList = ()=>{
return async(dispatch) =>{
const res = await.get(url) // url是請求后端的地址
// setChannel是源store在reducer中定義的action對象
dispatch(setChannel(res.data.channels))
}
}注意,因為給action對象傳遞參數(shù)了,所以參考上面的action傳參,需要源store中的action對象多定義一個action形參來接收數(shù)據(jù)
// channelStore.js (源)
reducers:{
setChannels(state,action){
state.channelList = action.payload
}
}(2).在需要的地方調(diào)用:
// App.js
const dispatch = useDispatch()
useEffect(()=>{
dispatch(fetchChannelList())
},[dispatch]到此這篇關(guān)于React 中使用 Redux Toolkit 狀態(tài)管理的文章就介紹到這了,更多相關(guān) Redux Toolkit 狀態(tài)管理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
從零開始搭建webpack+react開發(fā)環(huán)境的詳細步驟
這篇文章主要介紹了從零開始搭建webpack+react開發(fā)環(huán)境的詳細步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05
詳解React如何實現(xiàn)代碼分割Code Splitting
這篇文章主要為大家介紹了React如何實現(xiàn)代碼分割Code Splitting示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08
React?中使用?Redux?的?4?種寫法小結(jié)
這篇文章主要介紹了在?React?中使用?Redux?的?4?種寫法,Redux 一般來說并不是必須的,只有在項目比較復(fù)雜的時候,比如多個分散在不同地方的組件使用同一個狀態(tài),本文就React使用?Redux的相關(guān)知識給大家介紹的非常詳細,需要的朋友參考下吧2022-06-06
基于React.js實現(xiàn)原生js拖拽效果引發(fā)的思考
這篇文章主要為大家詳細介紹了基于React.js實現(xiàn)原生js拖拽效果,繼而引發(fā)的一系列思考,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-03-03

